我有一个WPF ListBox
控件,我将其ItemsSource
设置为项目对象的集合。如何将IsSelected
的{{1}}属性绑定到相应项目对象的ListBoxItem
属性,而不将该对象的实例设置为Selected
?
答案 0 :(得分:38)
只需覆盖ItemContainerStyle:
<ListBox ItemsSource="...">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding Selected}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
哦,顺便说一句,我想你会喜欢来自Dr.WPF的精彩文章:ItemsControl: A to Z。
希望这有帮助。
答案 1 :(得分:2)
我正在寻找代码中的解决方案,所以这里是它的翻译。
System.Windows.Controls.ListBox innerListBox = new System.Windows.Controls.ListBox();
//The source is a collection of my item objects.
innerListBox.ItemsSource = this.Manager.ItemManagers;
//Create a binding that we will add to a setter
System.Windows.Data.Binding binding = new System.Windows.Data.Binding();
//The path to the property on your object
binding.Path = new System.Windows.PropertyPath("Selected");
//I was in need of two way binding
binding.Mode = System.Windows.Data.BindingMode.TwoWay;
//Create a setter that we will add to a style
System.Windows.Setter setter = new System.Windows.Setter();
//The IsSelected DP is the property of interest on the ListBoxItem
setter.Property = System.Windows.Controls.ListBoxItem.IsSelectedProperty;
setter.Value = binding;
//Create a style
System.Windows.Style style = new System.Windows.Style();
style.TargetType = typeof(System.Windows.Controls.ListBoxItem);
style.Setters.Add(setter);
//Overwrite the current ItemContainerStyle of the ListBox with the new style
innerListBox.ItemContainerStyle = style;