5

Extended SelectionMode に WPF ListBox があります。

私がする必要があるのは、ListBox をデータ項目クラスの監視可能なコレクションにバインドすることです。これは簡単ですが、基本的には、IsSelected各 ListBoxItem のステータスをそれぞれのデータ項目のブール型プロパティにバインドします。

そして、ViewModel から選択されたアイテムと選択されていないアイテムを ListBox に入力できるように、双方向にする必要があります。

私は多くの実装を見てきましたが、どれもうまくいきません。それらには以下が含まれます:

  • ListBoxItem のスタイルに DataTrigger を追加し、状態アクション変更を呼び出す

これは、イベント ハンドラーを使用したコード ビハインドで実行できることはわかっていますが、ドメインの複雑さを考えると、非常に面倒です。ViewModel との双方向バインディングに固執したいと思います。

ありがとう。マーク

4

1 に答える 1

13

WPF では、IsSelected 状態のブール値プロパティを使用して、ListBox を項目のコレクションに簡単にバインドできます。あなたの質問が Silverlight に関するものである場合、残念ながら簡単にはうまくいきません。

public class Item : INotifyPropertyChanged
{
    // INotifyPropertyChanged stuff not shown here for brevity
    public string ItemText { get; set; }
    public bool IsItemSelected { get; set; }
}

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        Items = new ObservableCollection<Item>();
    }

    // INotifyPropertyChanged stuff not shown here for brevity
    public ObservableCollection<Item> Items { get; set; }
}

<ListBox ItemsSource="{Binding Items, Source={StaticResource ViewModel}}"
         SelectionMode="Extended">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="IsSelected" Value="{Binding IsItemSelected}"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ItemText}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
于 2012-11-28T18:02:41.540 に答える