首先先设定Style。其中触发器的Property为UIElement.IsKeyboardFocusWithin
<Style TargetType="{x:Type ListBoxItem}" x:Key="ListBoxItemStyle">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="true">
<Setter Property="IsSelected" Value="true"/>
</Trigger>
</Style.Triggers>
</Style>
然后修改ListBox的ItemContainerStyle
<Style TargetType="{x:Type ListBox}" x:Key="lbHorizontalItem">
<Setter Property="ItemContainerStyle" Value="{DynamicResource ListBoxItemStyle}"/>
</Style>
但是此时就会遇到一个问题,虽然在ListBox内部点击TextBox会切换样式,当点击ListBox外部的时候,即ListBox失去了焦点的时候,SelectedItem的样式就消失了,而这并不是我们想要到。用如下的解决方法
<Style TargetType="{x:Type ListBoxItem}" x:Key="ListBoxItemStyle">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="true">
<Setter Property="IsSelected" Value="true"/>
</Trigger>
<!--下面这个是新加的-->
<EventTrigger RoutedEvent="PreviewGotKeyboardFocus">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetProperty="(ListBoxItem.IsSelected)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>