我有一个处于扩展选择模式的 WPF 列表框。
我需要做的是将 ListBox 绑定(bind)到数据项类的可观察集合,这很简单,但本质上是将每个 ListBoxItem 的 IsSelected
状态绑定(bind)到各自的 bool 属性数据项。
而且,我需要它是双向的,以便我可以使用 ViewModel 中选定和未选定的项目填充 ListBox。
我已经研究了许多实现,但没有一个对我有用。它们包括:
- 将 DataTrigger 添加到 ListBoxItem 的样式并调用状态操作更改
我意识到这可以通过事件处理程序在代码隐藏中完成,但考虑到域的复杂性,它会非常困惑。我宁愿坚持使用 ViewModel 进行双向绑定(bind)。
谢谢。 标记
最佳答案
在 WPF 中,您可以轻松地将 ListBox 绑定(bind)到具有 IsSelected 状态 bool 属性的项目集合。如果您的问题是关于 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>
关于wpf - 如何将 ListBoxItem.IsSelected 绑定(bind)到 bool 数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13611113/