WPF如何让选中项和显示项不一样?
时间: 2024-02-27 12:55:54 浏览: 19
在WPF中,可以使用样式(Style)来实现选中项和显示项不一样的效果。具体实现方法如下:
1. 定义一个样式,设置选中项的背景色和前景色。
```xml
<Style x:Key="SelectedStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="Foreground" Value="White"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
```
2. 在ListBox中应用该样式,并设置显示项的背景色和前景色。
```xml
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="White"/>
<Setter Property="Foreground" Value="Black"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Style="{StaticResource SelectedStyle}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
这样就可以实现选中项和显示项不一样的效果了。其中,选中项的样式由SelectedStyle定义,显示项的样式由ListBox.ItemContainerStyle定义。在DataTemplate中,将TextBlock的样式设置为SelectedStyle,即可应用选中项的样式。