Binding the IsSelected property of ListBoxItem to a property on the object from it's source

后端 未结 2 1873
离开以前
离开以前 2020-12-17 09:19

I have a WPF ListBox control and I\'m setting its ItemsSource to a collection of item objects. How can I bind the IsSelected property

2条回答
  •  粉色の甜心
    2020-12-17 09:59

    I was looking for a solution in code, so here is the translation of that.

    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;
    

提交回复
热议问题