Подтвердить что ты не робот

Связывание свойства IsSelected ListBoxItem с объектом на объекте из его источника

У меня есть элемент управления WPF ListBox, и я устанавливаю его ItemsSource в коллекцию объектов объектов. Как связать свойство IsSelected свойства ListBoxItem с атрибутом Selected соответствующего объекта элемента без экземпляра объекта для установки как Binding.Source?

4b9b3361

Ответ 1

Просто переопределите ItemContainerStyle:

   <ListBox ItemsSource="...">
     <ListBox.ItemContainerStyle>
      <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="IsSelected" Value="{Binding Selected}"/>
      </Style>
     </ListBox.ItemContainerStyle>
    </ListBox>

О, кстати, я думаю, вам понравятся эти замечательные статьи от dr.WPF: ItemsControl: от А до Я.

Надеюсь, что это поможет.

Ответ 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;