C#WPF:ListBox项在添加鼠标进入和鼠标离开事件处理程序后未突出显示
我正在使用WPF在C#.NET3.5中开发一个应用程序。我在对话框中有一个列表框。当鼠标移到列表框中的项目上时,该项目将以蓝色背景突出显示 当鼠标移动到列表框中的项目上时,我想执行某些操作。因此,我为列表框项添加了鼠标进入和鼠标离开事件处理程序,如下所示: XAML代码:C#WPF:ListBox项在添加鼠标进入和鼠标离开事件处理程序后未突出显示,c#,.net,wpf,events,xaml,C#,.net,Wpf,Events,Xaml,我正在使用WPF在C#.NET3.5中开发一个应用程序。我在对话框中有一个列表框。当鼠标移到列表框中的项目上时,该项目将以蓝色背景突出显示 当鼠标移动到列表框中的项目上时,我想执行某些操作。因此,我为列表框项添加了鼠标进入和鼠标离开事件处理程序,如下所示: XAML代码: <ListBox Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="16,367,0,0" Width="181" H
<ListBox Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="16,367,0,0" Width="181" Height="186" >
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="MouseEnter" Handler="listBox1_ListBoxItem_MouseEnter"/>
<EventSetter Event="MouseLeave" Handler="listBox1_ListBoxItem_MouseLeave"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
添加事件处理程序后,当鼠标移到列表框项上时,列表框项不再突出显示。如何使突出显示与事件处理程序一起工作
感谢您提供的任何帮助。您正在覆盖ListBoxItem的默认样式,您应该使用BasedOn属性扩展它
<ListBox Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="16,367,0,0" Width="181" Height="186" >
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<EventSetter Event="MouseEnter" Handler="listBox1_ListBoxItem_MouseEnter"/>
<EventSetter Event="MouseLeave" Handler="listBox1_ListBoxItem_MouseLeave"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
丢失了默认样式。您可以重新添加颜色。但我喜欢Dtex的答案
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="MouseEnter" Handler="listBox1_ListBoxItem_MouseEnter"/>
<EventSetter Event="MouseLeave" Handler="listBox1_ListBoxItem_MouseLeave"/>
<Style.Resources>
<!-- Background of selected item when focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Green"/>
<!-- Background of selected item when not focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="LightGreen" />
</Style.Resources>
</Style>
</ListBox.ItemContainerStyle>
工作起来很有魅力!帮了大忙!谢谢。非常感谢。这是非常有用的信息。非常感谢你。我真的很感激。
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="MouseEnter" Handler="listBox1_ListBoxItem_MouseEnter"/>
<EventSetter Event="MouseLeave" Handler="listBox1_ListBoxItem_MouseLeave"/>
<Style.Resources>
<!-- Background of selected item when focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Green"/>
<!-- Background of selected item when not focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="LightGreen" />
</Style.Resources>
</Style>
</ListBox.ItemContainerStyle>