C# 在鼠标悬停时更改列表框项目的背景
我的列表框项目的样式如下:C# 在鼠标悬停时更改列表框项目的背景,c#,wpf,xaml,windows-7,C#,Wpf,Xaml,Windows 7,我的列表框项目的样式如下: <Style TargetType="ListBoxItem"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#007acc"/> <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSele
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#007acc"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="#007acc"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="WhiteSmoke"/>
</Style.Resources>
<Setter Property="Padding" Value="5,2,5,2"/>
<Setter Property="Margin" Value="0"/>
</Style>
<Style TargetType="ListBoxItem">
...
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
但是我不知道,当鼠标光标悬停在listboxitem上时,如何更改它的背景色。使用
鼠标指针和鼠标移动事件
在MouseEnter
事件中,更改背景色。在MouseLeave
上,恢复为“正常”颜色。这应该会产生您想要的效果。要达到您想要的效果,请在样式中使用一个,对ListBoxItem的属性进行操作。IsMouseOver是一个布尔属性,当鼠标悬停在ListBox项上时,它会自动设置为true
。(阅读以更好地了解此属性的工作原理。)
带有触发器的样式的XAML如下所示:
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#007acc"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="#007acc"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="WhiteSmoke"/>
</Style.Resources>
<Setter Property="Padding" Value="5,2,5,2"/>
<Setter Property="Margin" Value="0"/>
</Style>
<Style TargetType="ListBoxItem">
...
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
...
(如果您查看,您会注意到我在这里给出的示例与文档中给出的示例没有太大区别…)