将ListBoxItem的IsSelected属性绑定到来自源对象的属性

25
我有一个WPF的ListBox控件,我正在将它的ItemsSource设置为一个项对象的集合。如何将ListBoxItemIsSelected属性绑定到相应项对象的Selected属性上,而不需要实例化对象来设置Binding.Source
2个回答

52

只需覆盖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

希望这能有所帮助。


2
很遗憾,这在WinRT上不起作用,因为绑定在Setters上不受支持 - Trisped
这似乎不再可靠地工作了。绑定似乎只有在项目处于可见范围内时才会触发。我有一个包含100多个项目的列表,如果我使用CTRL+A选择所有条目,则仅具有其Selected属性的可见条目将被设置。向下滚动可以解决此问题。我猜这是WPF的性能优化,或可能是一个错误。 - UweB
对于解决方法,我发现以下内容很有帮助:请参见https://www.markwithall.com/programming/2017/05/14/accessing-wpf-listbox-selecteditems-using-mvvm.html,该链接位于文章底部。这是一项功能,而非错误 :) - UweB

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;

4
你好,BrandonS, 也许这两种解决方案都不错,但是请尽可能采用XML声明式方法来定义用户界面的行为。这样更多的人(交互开发人员等)可以理解并轻松修改它。 问候, - wacdany

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接