次の方法で共有


方法 : ListBoxItem を新しいデータ型に変換する

更新 : 2007 年 11 月

この例では、ListBoxItem のコンテンツを Thickness のインスタンスに変換する方法を説明します。この例で取り上げるのは ListBoxItem を Thickness のインスタンスに変換する方法のみですが、この方法は、互換性のある任意の型コンバータによる ListBoxItem の変換に応用できます。

使用例

次の例は、10 個の選択可能な ListBoxItem オブジェクトを持つ ListBox 要素を作成しています。SelectionChanged イベントは、後続のコード例で定義される ChangeMargin カスタム メソッドをトリガします。

Extensible Application Markup Language (XAML) の例の ListBoxItem はそれぞれ、要素の均一な余白を示すために使用される Thickness 値の 1 つを表します。ただし、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 イベント ハンドラが呼び出されます。このメソッドは、ListBoxItemThicknessConverter オブジェクトに渡します。このオブジェクトは、ListBoxItemContent プロパティを 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 +".";
        }

サンプル全体については、「Grid のマージンの変更のサンプル」を参照してください。

参照

処理手順

方法 : Margin プロパティを変更する

方法 : ThicknessConverter オブジェクトを使用する

参照

ListBox

ListBoxItem

ThicknessConverter