Choosing a WPF ListBoxItems

I have a ListBox with a fairly simple ItemTemplate containing a TextBlock and a Button . This appears as expected, but there is a problem. When I click on the contents of a ListBoxItem , that is, a text or a button, the row is not selected in the ListBox . If I click on the clean parts of the line, this will happen. I would like ListBoxItem be selected when I click anywhere in the row. What is needed to achieve this?

 <ListBox ItemsSource="{Binding SomeElements}"> <ListBox.ItemTemplate> <DataTemplate> <ListBoxItem Selected="ListBoxItem_Selected"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Title}"></TextBlock> <Button>Click</Button> </StackPanel> </ListBoxItem> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 
+4
source share
1 answer

@Natrium Nope, here is the problem here,

  • You need to remove the ListBoxItem inside the DataTemplate. A DataTemplate cannot have a ListBoxItem, and it will not work correctly. Everything that you define in the DataTemplate is automatically placed inside the ListBoxItem at runtime, so in your case this is what is created.
 ListBoxItem DataTemplate ListBoxItem StackPanel... 
  1. If you want to track the selection event, then you only need to catch the ListBox.SelectionChange event, you do not need to track the ListBoxItem_Selected.

Change your code.

 <ListBox ItemsSource="{Binding SomeElements}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Title}"></TextBlock> <Button>Click</Button> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 
+4
source

All Articles