방법: ListBoxItem을 새 데이터 형식으로 변환
업데이트: 2007년 11월
이 예제에서는 ListBoxItem의 콘텐츠를 Thickness의 인스턴스로 변환하는 방법을 보여 줍니다. 이 예제는 ListBoxItem을 Thickness의 인스턴스로 변환하는 구체적인 방법 외에도 다른 호환 가능 형식 변환기 사용하여 ListBoxItem을 변환할 수 있는 방법을 보여 줍니다.
예제
다음 예제에서는 선택할 수 있는 10개의 ListBoxItem 개체가 있는 ListBox 요소를 만듭니다. SelectionChanged 이벤트는 ChangeMargin 사용자 지정 메서드를 트리거합니다. 이 사용자 지정 메서드는 이후의 코드 예제에서 정의합니다.
XAML(Extensible Application Markup Language) 예제에서 각 ListBoxItem에는 요소의 균일한 여백을 설명하는 데 사용되는 Thickness 값이 있습니다. 하지만 ListBoxItem을 사용하여 Thickness의 인스턴스를 표현하려면 먼저 해당 요소를 올바른 데이터 형식으로 변환해야 합니다. 이러한 변환은 이후의 코드 예제에 나와 있습니다.
<ListBox Grid.Row="0" Grid.Column="1"
Width="50" Height="50"
VerticalAlignment="Top"
SelectionChanged="ChangeMargin">
<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 선택 항목을 변경하면 이벤트 처리기 ChangeMargin이 호출됩니다. 이 메서드는 ThicknessConverter 개체에 ListBoxItem을 전달하고 이는 ListBoxItem의 Content 속성을 Thickness의 인스턴스로 변환합니다. Content의 값은 ToString 메서드를 사용하여 이미 문자열로 변환되었음을 유의해야 합니다. 그런 다음 이 값은 text1 개체의 Margin으로 설정됩니다.
Private Sub ChangeMargin(ByVal sender As Object, ByVal args As SelectionChangedEventArgs)
Dim li As ListBoxItem = CType(CType(sender, ListBox).SelectedItem, ListBoxItem)
Dim myThicknessConverter As ThicknessConverter = New ThicknessConverter()
Dim th1 As Thickness = CType(myThicknessConverter.ConvertFromString(li.Content.ToString()), Thickness)
text1.Margin = th1
Dim st1 As String = CType(myThicknessConverter.ConvertToString(text1.Margin), String)
gridVal.Text = "The Margin property is set to " + st1 + "."
End Sub
private void ChangeMargin(object sender, SelectionChangedEventArgs args)
{
ListBoxItem li = ((sender as ListBox).SelectedItem as ListBoxItem);
ThicknessConverter myThicknessConverter = new ThicknessConverter();
Thickness th1 = (Thickness)myThicknessConverter.ConvertFromString(li.Content.ToString());
text1.Margin = th1;
String st1 = (String)myThicknessConverter.ConvertToString(text1.Margin);
gridVal.Text = "The Margin property is set to " + st1 +".";
}
전체 샘플을 보려면 모눈의 여백 변경 샘플을 참조하십시오.