Question

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}"/>
Was it helpful?

Solution

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}"/>

OTHER TIPS

Try. You can take away the background color but that will show you how big the TextBlock is.

     Background="Beige" HorizontalAlignment="Stretch"

Are you sure the extra white space you are clickin on is "inside" your ListBox. Are you sure your ListBox is spanned across that much width?

Coz it doesnt seem to happen in my case.... (following ListBox is a child of a Window)

 <Window x:Class="WpfApplicationPathToImage.Window4"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window4" Height="100" Width="100">
    <ListBox SelectionChanged="ListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Text}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemsSource>
            <x:Array Type="{x:Type TextBlock}">
                <TextBlock Text="Text1"/>
                <TextBlock Text="Text2"/>
                <TextBlock Text="Text3"/>
                <TextBlock Text="Text4"/>
                <TextBlock Text="Text5"/>
                <TextBlock Text="Text6"/>
            </x:Array>
        </ListBox.ItemsSource>
    </ListBox>
 </Window>

My ListBox_SelectionChanged is correctly called even if I click the white space outside the item level TextBlock boundaries (provided that I am actually clicking somewhere inside the ListBox).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top