Search code examples
wpfdata-bindinglistboxitemselected

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


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 of the ListBoxItem to a Selected property of a corresponding item object without having an instance of the object to set as a Binding.Source?


Solution

  • 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.