5

我想更改 ListBoxItem 的背景颜色

搜索后我决定使用这个

<ListBox>
        <ListBox.Resources>
            <!-- Background of selected item when focussed -->
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Blue" />
            <!-- Background of selected item when not focussed -->
            <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
                             Color="Blue" />

        </ListBox.Resources>
        <TextBlock>fdfsdf1</TextBlock>
        <TextBlock>fdfsdf3</TextBlock>
        <TextBlock>fdfsdf5</TextBlock>
        <TextBlock>fdfsdf3</TextBlock>
        <TextBlock>fdfsdf4</TextBlock>
    </ListBox>

当listBoxItem集中时,背景是蓝色的,但是当所选的ListBoxItem失去焦点时,背景会变为灰色。失去焦点时如何使背景保持蓝色?

4

4 回答 4

14

如果您的意思是当它被选中但处于非活动状态时尝试InactiveSelectionHighlightBrushKey

    <ListBox.Resources>
        <!-- Background of selected item when focussed -->
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                         Color="Blue" />
        <!-- Background of selected item when not focussed -->
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
                         Color="Blue" />

    </ListBox.Resources>
于 2013-03-15T11:30:38.103 回答
7

试试这个

<ListBox>
        <ListBox.Resources>
            <Style TargetType="ListBoxItem">
                <Setter Property="Background" Value="Blue" />
            </Style>
        </ListBox.Resources>
        <TextBlock>fdfsdf1</TextBlock>
        <TextBlock>fdfsdf3</TextBlock>
        <TextBlock>fdfsdf5</TextBlock>
        <TextBlock>fdfsdf3</TextBlock>
        <TextBlock>fdfsdf4</TextBlock>
    </ListBox>
于 2013-03-15T11:33:04.233 回答
1

如果您认为系统颜色键不适合您,那么您可以通过为 ListboxItems 创建新样式来强制它,如下所示。

        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="Silver"/>
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
于 2013-03-15T11:38:38.887 回答
0

这是我用来为 ListBox 的活动/非活动项选择颜色的方法:

<ListBox Name="lbExample" SelectionMode="Multiple">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <...>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Resources>
            <!-- Background of selected item when not focussed -->
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Background" Value="AntiqueWhite" />
            </Style>

            <!-- Background of selected item when focussed -->
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGreen" />
    </ListBox.Resources>
</ListBox>
于 2015-02-27T12:57:42.490 回答