Home > Back-end >  ListBoxItem with Runs does not allow mouse selection on text
ListBoxItem with Runs does not allow mouse selection on text

Time:01-19

I'm creating a ListBox with items that have a portion of the text highlighted. This would normally be a search term, but for this simple example I'm just using "NEW". The highlighting works (lifted from a tutorial), but when mouse is over the text portion of the ListBoxItem it does not get the blue highlight and cannot be selected. Clicking in the white space to the right of the text does allow it to be selected. How can I fix the Runs so that they accept the mouse hover and selection?

Sample VS solution utilizing WPF: https://www.dropbox.com/s/m8bhogp3k75rkoj/RunHoverTest.zip?dl=0 Left side of window is normal ListBox, right side is with highlighting applied in OnLoaded event.

I looked into adding a mouse hover event to the Run but got stuck on how to pass it down to the TextBlock. Any suggestion to do the highlighting differently to make it work is also welcome. Thanks.

CodePudding user response:

Create an explicit DataTemplate in the view:

<ListBox Name="HighlightedListBox" Grid.Column="1" ItemsSource="{Binding AllStates}"
    Loaded="ListBox_OnLoaded">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This should make the items selectable.

  • Related