问题描述
我在扩展选择模式中有一个 WPF 列表框.
I have a WPF ListBox in Extended SelectionMode.
我需要做的是将 ListBox 绑定到数据项类的可观察集合,这很容易,但本质上,将每个 ListBoxItem 的 IsSelected
状态绑定到相应的布尔属性数据项.
What I need to do is bind the ListBox to an observable collection of a data item class, which is easy, but essentially, bind the IsSelected
status of each ListBoxItem to a boolean property in the respective data item.
而且,我需要它是双向的,以便我可以使用 ViewModel 中的选定和未选定项目填充 ListBox.
And, I need it to be two-way, so that I can populate the ListBox with selected and unselected items from the ViewModel.
我查看了许多实现,但没有一个对我有用.它们包括:
I've looked at a number of implementations but none work for me. They include:
- 向 ListBoxItem 的样式添加 DataTrigger 并调用状态操作更改
我意识到这可以使用事件处理程序在代码隐藏中完成,但考虑到域的复杂性,它会非常混乱.我宁愿坚持使用 ViewModel 进行双向绑定.
I realise this can be done in code-behind with an event handler, but given the complexity of the domain it would be horribly messy. I'd rather stick to two-way Binding with the ViewModel.
谢谢.标记
推荐答案
在 WPF 中,您可以轻松地将 ListBox 绑定到具有 IsSelected 状态的布尔属性的项目集合.如果您的问题是关于 Silverlight,恐怕它不会以简单的方式工作.
In WPF you can easily bind your ListBox to a collection of items with a boolean property for the IsSelected state. If your question is about Silverlight, i'm afraid it won't work the easy way.
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>
这篇关于如何将 ListBoxItem.IsSelected 绑定到布尔数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!