4

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>
1

1 Answer 1

4

@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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.