I have a WPF ListBox whose items are TextBlocks. When I click on the text the SelectionChanged handler is called as expected. However, if I click inside the item, but not directly over the text the handler is not called. This is more apparent when the text items are of widely varying lengths. If I have two items:
foo
exclamation
The "foo" item has a lot of space to the right which doesn't respond to the click
<DataTemplate x:Key="NameTemplate">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
...
<ListBox SelectionChanged="ListItemSelected" ItemTemplate="{StaticResource NameTemplate}"/>
I found that the following works, but it seems rather verbose...
<ListBox SelectionChanged="ListItemSelected" ItemTemplate="{StaticResource NameTemplate}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Any ideas on how to do this more concisely? Or a way to put this in the ItemTemplate? I couldn't find a way to do the same in the template.
The orig without that was just:
<ListBox SelectionChanged="ListItemSelected" ItemTemplate="{StaticResource NameTemplate}"/>