이 예제에서는 Canvas 요소의 위치 지정 메서드를 사용하여 자식 콘텐츠의 위치를 지정하는 방법을 보여 줍니다. 이 예제에서는 ListBoxItem의 콘텐츠를 사용하여 위치 지정 값을 나타내고 값을 위치 지정을 위한 필수 인수인 Double의 인스턴스로 변환합니다. 그런 다음 값은 다시 문자열로 변환되고 GetLeft 메서드를 통해 TextBlock 요소에 텍스트로 표시됩니다.
예제
다음 예제에서는 11개의 선택 가능한 ListBoxItem 요소가 있는 ListBox 요소를 만듭니다. SelectionChanged 이벤트는 이후 코드 블록에서 정의되는 ChangeLeft 사용자 지정 메서드를 트리거합니다.
각 ListBoxItem은 Canvas의 SetLeft 메서드가 사용하는 인수 중 하나인 Double 값을 나타냅니다. 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 개체에 전달하며 이 개체는 ListBoxItem의 Content를 Double의 인스턴스로 변환합니다. 이 값은 ToString 메서드를 통해 이미 String으로 변환되었다는 점을 유의하십시오. 그런 다음 이 값은 text1 개체의 위치를 변경하기 위해 다시 Canvas의 SetLeft 및 GetLeft 메서드에 전달됩니다.
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;
}