我有一个 WPFListBox
控件,并将其设置ItemsSource
为项目对象的集合。如何将 的IsSelected
属性绑定ListBoxItem
到Selected
相应项目对象的属性,而无需将对象的实例设置为Binding.Source
?
问问题
19202 次
2 回答
49
只需覆盖 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。
希望这可以帮助。
于 2009-12-09T17:51:08.957 回答
3
我一直在寻找代码中的解决方案,所以这里是它的翻译。
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;
于 2009-12-10T15:22:26.103 回答