是的,我知道这可能是重复的,但是我看到的答案不起作用(或者我误会了)。我无法更改所选ListViewItem的背景颜色!这个例子非常简单和基本。
我有一个这样定义的列表源:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace WpfApp5
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public List<ListViewItem> List
{
get
{
var list = new List<ListViewItem>();
for (int i = 0; i < 10; i++)
{
list.Add(new ListViewItem
{
Height = 40,
Content = i,
VerticalContentAlignment = VerticalAlignment.Center,
HorizontalContentAlignment = HorizontalAlignment.Center
});
}
return list;
}
}
}
}
XAML就是:
<Window x:Class="WpfApp5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp5"
x:Name="MainWindowName"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ResourceDictionary>
<Style TargetType="{x:Type ListViewItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Black" />
</Style.Resources>
<Style.Triggers>
<Trigger Property="IsSelected" Value="true" >
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding ElementName=MainWindowName, Path=List}" />
</Grid>
</Window>
据我了解,有些人说标准的样式触发器有效,而另一些人说我需要设置SystemColors.HighlightBrushKey
。无论如何,以上样式对于所选背景完全不变。前景颜色更改正确了吗?
有人可以发布正确的XAML来将所选ListViewItem的背景更改为黑色吗?
谢谢。
答案 0 :(得分:3)
问题是您不能只设置前景/背景并期望它能正常工作,还有其他各种事情,例如高光等。在您的情况下,最简单的事情可能就是将ListViewItem ControlTemplate替换为一个TextBlock,然后可以通过触发器设置前景/背景。
或者换句话说,只需执行以下操作:
<Window.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Grid Background="{TemplateBinding Background}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
<TextBlock Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center">
<ContentPresenter />
</TextBlock>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
<Style.Triggers>
<Trigger Property="IsSelected" Value="False">
<Setter Property="Foreground" Value="Black" />
<Setter Property="Background" Value="PaleGoldenrod" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Yellow" />
<Setter Property="Background" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>