1

I have a listbox with a DataTemplate for the items. Inside my template, I have a label and 3 buttons.

My problem is that when i click the buttons, the listboxitem never become selected since the button handles the event.

Is there a way I could make the event still bubble up the tree so my listboxitem become selected and still fire the click on the button?

animuson
  • 53,861
  • 28
  • 137
  • 147
SiriusNik
  • 561
  • 2
  • 7
  • 19
  • 2
    See this question: http://stackoverflow.com/questions/662201/why-doesnt-button-click-event-bubble-up-visual-tree-to-stackpanel-as-msdn-arti – CodingGorilla Sep 22 '11 at 15:49
  • This question has a better answer: http://stackoverflow.com/q/7013538/302677 – Rachel Sep 22 '11 at 17:02

1 Answers1

-1

Put this in your ListBox.Resources

<Style TargetType="{x:Type ListBoxItem}">
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>

And this in the Code Behind

protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
    ListBoxItem item = (ListBoxItem)sender;
    item.IsSelected = true;
}

You could use the following code as well which doesn't use code-behind, however it only keeps the ListBoxItem selected for as long as it has KeyBoard focus. Once focus leaves, the item becomes unselected

<Style TargetType="ListBoxItem">
  <Style.Triggers>
    <Trigger Property="IsKeyboardFocusWithin" Value="True">
      <Setter Property="IsSelected" Value="True" />
    </Trigger>
  </Style.Triggers>
</Style>
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • You might want to give credit where it's due: http://stackoverflow.com/questions/653524/selecting-a-textbox-item-in-a-listbox-does-not-change-the-selected-item-of-the-l – CodingMadeEasy Feb 01 '16 at 03:50
  • @CodingMadeEasy That already has an upvote from me from a long time back :) I copied this answer from [this answer of mine](http://stackoverflow.com/a/7013960/302677), its a very common question here on the site. – Rachel Feb 01 '16 at 14:45
  • Well by restating the answer, how is that helping the community? It's creating a duplication of answers, not a variety of answers. You should've referred the OP to your other answer. – CodingMadeEasy Feb 01 '16 at 20:07
  • @CodingMadeEasy They're not the same question, so don't deserve the same answer :) Sometimes I do vote to close as duplicate, but I have to be careful now because I have a gold wpf badge and it no longer takes 5 votes if I do. This answer is from years ago though, I like to think I've improved my answer quality since then :) – Rachel Feb 01 '16 at 21:23