示例:
下面的示例演示如何创建和使用实例 GridLengthConverter。 该示例定义了一个调用changeCol
的自定义方法,该方法将传递给ListBoxItemGridLengthConverterContent将 a ListBoxItem 转换为实例的GridLength自定义方法。 然后,转换后的值作为元素的属性Width的值ColumnDefinition传递回。
该示例还定义了第二个称为 changeColVal
的自定义方法。 此自定义方法将 Value a 转换为 a SliderString,然后将该值作为元素的传递回ColumnDefinitionWidth。
请注意,单独的可扩展应用程序标记语言 (XAML) 文件定义一个 ListBoxItem内容。
private void changeColVal(object sender, RoutedEventArgs e)
{
txt1.Text = "Current Grid Column is " + hs1.Value.ToString();
}
private void changeCol(object sender, SelectionChangedEventArgs args)
{
ListBoxItem li = ((sender as ListBox).SelectedItem as ListBoxItem);
GridLengthConverter myGridLengthConverter = new GridLengthConverter();
if (hs1.Value == 0)
{
GridLength gl1 = (GridLength)myGridLengthConverter.ConvertFromString(li.Content.ToString());
col1.Width = gl1;
}
else if (hs1.Value == 1)
{
GridLength gl2 = (GridLength)myGridLengthConverter.ConvertFromString(li.Content.ToString());
col2.Width = gl2;
}
else if (hs1.Value == 2)
{
GridLength gl3 = (GridLength)myGridLengthConverter.ConvertFromString(li.Content.ToString());
col3.Width = gl3;
}
}
Private Sub changeColVal(ByVal sender As Object, ByVal args As RoutedPropertyChangedEventArgs(Of Double))
txt1.Text = "Current Grid Column is " + hs1.Value.ToString()
End Sub
Private Sub changeCol(ByVal sender As Object, ByVal args As SelectionChangedEventArgs)
Dim li1 As ListBoxItem = CType(CType(sender, ListBox).SelectedItem, ListBoxItem)
Dim myGridLengthConverter As System.Windows.GridLengthConverter = New System.Windows.GridLengthConverter()
If (hs1.Value = 0) Then
Dim gl1 As GridLength = CType(myGridLengthConverter.ConvertFromString(li1.Content.ToString()), GridLength)
col1.Width = gl1
ElseIf (hs1.Value = 1) Then
Dim gl2 As GridLength = CType(myGridLengthConverter.ConvertFromString(li1.Content.ToString()), GridLength)
col2.Width = gl2
ElseIf (hs1.Value = 2) Then
Dim gl3 As GridLength = CType(myGridLengthConverter.ConvertFromString(li1.Content.ToString()), GridLength)
col3.Width = gl3
End If
End Sub