如何将ListBoxItem.IsSelected绑定到布尔数据属性

时间:2012-11-28 17:36:52

标签: wpf silverlight

我在Extended SelectionMode中有一个WPF ListBox。

我需要做的是将ListBox绑定到数据项类的可观察集合,这很容易,但实际上,每个ListBoxItem的IsSelected状态绑定到相应数据项中的布尔属性。

并且,我需要它是双向的,以便我可以使用ViewModel中的选定和未选定项填充ListBox。

我看了很多实现,但没有一个适合我。它们包括:

  • 将DataTrigger添加到ListBoxItem的样式并调用状态操作更改

我意识到这可以通过事件处理程序在代码隐藏中完成,但考虑到域的复杂性,它将非常混乱。我宁愿坚持使用ViewModel进行双向绑定。

感谢。 标记

1 个答案:

答案 0 :(得分:11)

在WPF中,您可以轻松地将ListBox绑定到具有IsSelected状态的布尔属性的项集合。如果您的问题是关于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>
相关问题