如何更改ListViewItem的背景颜色?

时间:2017-04-15 14:49:23

标签: c# wpf listviewitem

我一直在尝试这段代码:

<Style TargetType="ListViewItem">
                    <Setter Property="OverridesDefaultStyle" Value="True" />
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="ListViewItem">
                                <ContentPresenter />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="Blue" />
                            <Setter Property="Background" Value="Red" />
                        </Trigger>
                    </Style.Triggers>
                </Style>

但是我发现只有文字颜色会改变,但背景仍然保持不变。当我切换到其他触发器类型时,我发现这种行为不会改变,即使我只是这样做:

<Style TargetType="ListViewItem">
                <Setter Property="OverridesDefaultStyle" Value="True" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <ContentPresenter />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="Background" Value="Red" />
            </Style>

1 个答案:

答案 0 :(得分:0)

最后,我找到了解决问题的方法。特别感谢@TiberiumFusion的一个很好的提示。虽然,这个解决方案并不像我想的那么好。

<Style TargetType="ListViewItem">
                <Setter Property="OverridesDefaultStyle" Value="True" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <Border x:Name="border">
                                <ContentPresenter />
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver"  Value="True">
                                    <Setter Property="Control.Foreground" TargetName="border" Value="Blue" />
                                    <Setter Property="Control.Background" TargetName="border" Value="Red" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>