Question

I have a ListBox with a rather simple ItemTemplate defined - containing a TextBlock and a Button. This displays like expected, but there is a problem though. When I click the content of the ListBoxItem, i.e. the text or the button, the line doesn't get selected in the ListBox. If I click the blank parts of the line it does. I'd like the ListBoxItem to be selected when I click anywhere on the line. What's 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>
Was it helpful?

Solution

@Natrium Nope, the problem is different here,

  1. You need to remove ListBoxItem inside DataTemplate. DataTemplate can not have item ListBoxItem, and it will not work correctly. Whatever you define in DataTemplate is automatically put inside ListBoxItem at runtime, so in your case, this is what it gets created.
ListBoxItem
    DataTemplate
        ListBoxItem
            StackPanel...
  1. If you want to track selection event, then you should only catch ListBox.SelectionChange event, you dont need to track ListBoxItem_Selected.

Change your code to this.

<ListBox ItemsSource="{Binding SomeElements}">
    <ListBox.ItemTemplate>
        <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Title}"></TextBlock>
                    <Button>Click</Button>
                </StackPanel>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top