Wpf 如何将ListBoxItem.IsSelected绑定到布尔数据属性
我有一个扩展选择模式下的WPF列表框 我需要做的是将ListBox绑定到一个数据项类的可观察集合,这很简单,但本质上是将每个ListBoxItem的Wpf 如何将ListBoxItem.IsSelected绑定到布尔数据属性,wpf,silverlight,Wpf,Silverlight,我有一个扩展选择模式下的WPF列表框 我需要做的是将ListBox绑定到一个数据项类的可观察集合,这很简单,但本质上是将每个ListBoxItem的IsSelected状态绑定到相应数据项中的布尔属性 而且,我需要它是双向的,这样我就可以用ViewModel中的选定项和未选定项填充列表框 我看过很多实现,但没有一个适合我。这些措施包括: 向ListBoxItem的样式添加DataTrigger并调用状态操作更改 我意识到这可以通过使用事件处理程序在代码隐藏中完成,但考虑到域的复杂性,这将是非
IsSelected
状态绑定到相应数据项中的布尔属性
而且,我需要它是双向的,这样我就可以用ViewModel中的选定项和未选定项填充列表框
我看过很多实现,但没有一个适合我。这些措施包括:
- 向ListBoxItem的样式添加DataTrigger并调用状态操作更改
标记在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; }
}
公共类项:INotifyPropertyChanged
{
//为简洁起见,此处未显示INotifyPropertyChanged内容
公共字符串ItemText{get;set;}
公共布尔IsItemSelected{get;set;}
}
公共类视图模型:INotifyPropertyChanged
{
公共视图模型()
{
Items=新的ObservableCollection();
}
//为简洁起见,此处未显示INotifyPropertyChanged内容
公共ObservableCollection项{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>