Search code examples
wpflistboxselectionlistboxitemselectionchanged

Click/focus on a ListBoxItem's content doesn't bubble up


I've got a ListBox that's declared like this:

<ListBox ItemsSource="{Binding Contracts}" SelectedItem="{Binding SelectedContract}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <ListBoxItem Content="{Binding Name}">
        <ListBoxItem.ToolTip>
          <Grid>
            [code omitted for reasons of clarity]
          </Grid>
        </ListBoxItem.ToolTip>
      </ListBoxItem>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

I expected the normal selection behavior since I play with the item's ToolTip rather than its content structure. However, clicking an item's name doesn't focus/select that item. Only by clicking that tiny space between each item (easiest way would be the space between an item's name and the ListBox's border) the item gets focused/selected.

Of course, I googled around and thought I'd found the culprit (event doesn't bubble up). But any solution provided here on SO or elsewhere, e. g. adding code like this:

<ListBoxItem.Style>
  <Style TargetType="ListBoxItem">
    <Style.Triggers>
      <Trigger Property="IsKeyboardFocusWithin" Value="True">
        <Setter Property="IsSelected" Value="True" />
      </Trigger>
    </Style.Triggers>
  </Style>
</ListBoxItem.Style>

turned out to not solve the problem. So, I assume I do something wrong and I'm just too blind to see it. And while there might be solutions using code-behind, I prefer to stick with clean and pure XAML.

Please help me, understanding my mistake and solving it.


Solution

  • if the purpose is add ToolTip for ListBoxItem, you can use ItemContainerStyle. ListBox creates ListBoxItems for each databound item, adding ListBoxItem into DataTemplate isn't necessary, if it breaks some functionality, try to avoid it

    <ListBox>
    
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <Setter Property="ToolTip">
                    <Setter.Value>
                        <Grid>
                            <TextBlock Text="{Binding .}"/>
                        </Grid>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding .}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    
    </ListBox>
    

    edit: I used Snoop app to check your variant with ListBoxItem in DataTemplate. There is 2 ListBoxItems in visual tree of each ListBox element, maybe one of prevent selection of another