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

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


Just override ItemContainerStyle:

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

Oh, by the way, I think you'd like this wonderful articles from dr.WPF: ItemsControl: A to Z.

Hope this helps.


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 setterSystem.Windows.Data.Binding binding = new System.Windows.Data.Binding();//The path to the property on your objectbinding.Path = new System.Windows.PropertyPath("Selected"); //I was in need of two way bindingbinding.Mode = System.Windows.Data.BindingMode.TwoWay;//Create a setter that we will add to a styleSystem.Windows.Setter setter = new System.Windows.Setter();//The IsSelected DP is the property of interest on the ListBoxItemsetter.Property = System.Windows.Controls.ListBoxItem.IsSelectedProperty;setter.Value = binding;//Create a styleSystem.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;