列表框WPF项目背景颜色

时间:2013-03-15 11:21:39

标签: c# wpf xaml

我想更改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 个答案:

答案 0 :(得分: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>

答案 1 :(得分:5)

试试这个

<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>

答案 2 :(得分:0)

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

        <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>

答案 3 :(得分: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>