如何:获取或设置画布定位属性

下面的示例演示如何使用 Canvas 元素的定位方法来定位子内容。 此示例使用 ListBoxItem 中的内容来表示定位值,并将这些值转换为 Double(定位时必需的参数)的实例。 然后,使用 GetLeft 方法将这些值重新转换为字符串,并在 TextBlock 元素中将其显示为文本。

示例

下面的示例将创建具有十一个可选 ListBoxItem 元素的 ListBox 元素。 SelectionChanged 事件触发 ChangeLeft 自定义方法,后续代码块将定义该方法。

每个 ListBoxItem 都表示一个 Double 值,该值是 CanvasSetLeft 方法可接受的参数之一。 要使用 ListBoxItem 来表示 Double 的实例,必须先将 ListBoxItem 转换为正确的数据类型。

<ListBox Grid.Column="1" Grid.Row="1" VerticalAlignment="Top" Width="60" Margin="10,0,0,0" SelectionChanged="ChangeLeft">
  <ListBoxItem>Auto</ListBoxItem>      
  <ListBoxItem>10</ListBoxItem>
  <ListBoxItem>20</ListBoxItem>
  <ListBoxItem>30</ListBoxItem>
  <ListBoxItem>40</ListBoxItem>
  <ListBoxItem>50</ListBoxItem>
  <ListBoxItem>60</ListBoxItem>
  <ListBoxItem>70</ListBoxItem>
  <ListBoxItem>80</ListBoxItem>
  <ListBoxItem>90</ListBoxItem>
  <ListBoxItem>100</ListBoxItem>      
</ListBox>
<ListBox Grid.Column="1" Grid.Row="1" VerticalAlignment="Top" Width="60" Margin="10,0,0,0" SelectionChanged="ChangeLeft">
  <ListBoxItem>Auto</ListBoxItem>      
  <ListBoxItem>10</ListBoxItem>
  <ListBoxItem>20</ListBoxItem>
  <ListBoxItem>30</ListBoxItem>
  <ListBoxItem>40</ListBoxItem>
  <ListBoxItem>50</ListBoxItem>
  <ListBoxItem>60</ListBoxItem>
  <ListBoxItem>70</ListBoxItem>
  <ListBoxItem>80</ListBoxItem>
  <ListBoxItem>90</ListBoxItem>
  <ListBoxItem>100</ListBoxItem>      
</ListBox>

当用户更改 ListBox 选择时,将会调用 ChangeLeft 自定义方法。 此方法会将 ListBoxItem 传递给 LengthConverter 对象,该对象会将 ListBoxItemContent 转换为 Double 的实例(请注意,已使用 ToString 方法将此值转换为 String)。 此值随后将回传给 CanvasSetLeftGetLeft 方法,以便更改 text1 对象的位置。

Private Sub ChangeLeft(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
    Dim li As ListBoxItem = CType(CType(sender, ListBox).SelectedItem, ListBoxItem)
    Dim myLengthConverter As New LengthConverter
    Dim db1 As Double = CType(myLengthConverter.ConvertFromString(li.Content.ToString()), Double)
    Canvas.SetLeft(text1, db1)
    Dim st1 As String = CType(myLengthConverter.ConvertToString(Canvas.GetLeft(text1)), String)
    canvasLeft.Text = "Canvas.Left = " + st1
End Sub
        private void ChangeLeft(object sender, SelectionChangedEventArgs args)
        {
            ListBoxItem li = ((sender as ListBox).SelectedItem as ListBoxItem);
            LengthConverter myLengthConverter = new LengthConverter();
            Double db1 = (Double)myLengthConverter.ConvertFromString(li.Content.ToString());
            Canvas.SetLeft(text1, db1);
            String st1 = (String)myLengthConverter.ConvertToString(Canvas.GetLeft(text1));
            canvasLeft.Text = "Canvas.Left = " + st1;
        }

请参见

参考

Canvas

ListBoxItem

LengthConverter

概念

面板概述