I have a listbox with a DataTemplate for the items. Inside my template, 开发者_Python百科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?
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>
精彩评论