wpf Listbox 鼠标悬浮
时间: 2023-09-04 16:12:06 浏览: 164
要实现WPF Listbox的鼠标悬浮效果,可以使用ListBox.ItemContainerStyle和Trigger来实现。具体步骤如下:
1. 在ListBox中添加ItemContainerStyle属性,指定ListBoxItem的样式:
```
<ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}">
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
</ListBox>
```
2. 在资源字典中定义ListBoxItemStyle样式:
```
<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Padding" Value="5" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="border" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#FFCCE5FF" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="border" Property="Background" Value="#FF007ACC" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
3. 在ListBoxItemStyle样式中添加IsMouseOver Trigger,指定鼠标悬浮时的背景色。
4. 可以根据需要,添加IsSelected Trigger,指定选中时的样式。
这样就可以实现WPF Listbox的鼠标悬浮效果了。
阅读全文