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

ms1*_*s10 5 silverlight wpf

我在Extended SelectionMode中有一个WPF ListBox.

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

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

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

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

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

谢谢.标记

Cle*_*ens 12

在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; }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)