为什么我不能在 WPF 中设置选定 ListBoxItem 的背景颜色? [英] Why can't I set the background color of a selected ListBoxItem in WPF?

查看:25
本文介绍了为什么我不能在 WPF 中设置选定 ListBoxItem 的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击 ListBoxItem 时,我希望它是一个大胆的较大字体红色背景黄色

When a user clicks on an ListBoxItem, I want to it to be a bold larger font red background yellow

除背景外,一切正常.所选项目似乎有标准(蓝色)背景.如何覆盖它并更改选定的背景黄色?

Everything works except the background. It seems that there is a standard (blue) background for the selected item. How do I override that and change the selected background yellow?

代码如下:

<Window x:Class="AlternateListBox2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    xmlns:local="clr-namespace:AlternateListBox2">
    <Window.Resources>
        <local:Countries x:Key="countries"/>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Content" Value="{Binding Path=Name}"/>
            <Setter Property="Margin" Value="2"/>
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="FontWeight" Value="Bold"/>
                    <Setter Property="FontSize" Value="18"/>
                    <Setter Property="Background" Value="Yellow"/>
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>

        </Style>
    </Window.Resources>
    <StackPanel>
        <ListBox
            ItemsSource="{Binding Source={StaticResource countries}}"
            Width="100"
            Margin="10"
            HorizontalAlignment="Left"
            />
    </StackPanel>
</Window>

推荐答案

可以做的简单很多.所选 ListBox 项的背景颜色取自 SystemColors.因此,您需要做的是覆盖 ListBox 资源中的 SystemColors:

It can be done a lot simpler. The Background color for the selected ListBox items are taken from the SystemColors. So, what you need to do is override the SystemColors in the Resources of your ListBox:

<ListBox.Resources>
    <!--Selected color when the ListBox is focused-->
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" />
    <!--Selected color when the ListBox is not focused-->
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Yellow" />
</ListBox.Resources>

这篇关于为什么我不能在 WPF 中设置选定 ListBoxItem 的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆