更改ListBox项的选择颜色

时间:2014-07-24 14:46:08

标签: c# wpf xaml checkbox listbox

我有一个正常的ListBox,我想将选择颜色更改为红色。这是我到目前为止所做的事情。

<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                         Color="red" />
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
                         Color="red" />
    </Style.Resources>
</Style>

它在工作。 SelectedItem是红色的,即使它没有焦点也保持红色。

这是我真正的问题:在我的网格中我也有一个CheckBox,我希望只有选中CheckBox才能应用上述样式。

因此,如果选中CheckBox,我希望选择颜色为红色,如果取消选中CheckBox,则为蓝色(或默认颜色)。

我浏览了网页而无法找到任何内容,所以我正在寻求帮助。

2 个答案:

答案 0 :(得分:1)

您可以有两种不同的样式 -

  1. 包含所有setter和触发器的默认样式。

  2. 空白样式,其中定义了资源,并使此样式为 BasedOn 默认样式,以便所有setter和触发器都从默认样式继承。

    < / LI>

    然后你可以根据checkBox检查状态交换 ItemContainerStyle


    示例:

    <StackPanel>
        <StackPanel.Resources>
            <Style x:Key="myLBStyleDefault">
              <!-- All setters and triggers go here -->
            </Style>
            <Style x:Key="myLBStyleWithRed"
                   BasedOn="{StaticResource myLBBaseStyle}"
                   TargetType="{x:Type ListBoxItem}">
                <Style.Resources>
                    <SolidColorBrush
                        x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                        Color="Red" />
                    <SolidColorBrush
                        x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
                        Color="Red" />
                </Style.Resources>
            </Style>
        </StackPanel.Resources>
        <CheckBox x:Name="chk"/>
        <ListBox>
            <ListBox.Style>
                <Style TargetType="ListBox">
                    <Setter Property="ItemContainerStyle"
                            Value="{StaticResource myLBStyleDefault}"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsChecked, ElementName=chk}" 
                                     Value="True">
                            <Setter Property="ItemContainerStyle"
                                    Value="{StaticResource myLBStyleWithRed}"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ListBox.Style>
        </ListBox>
    </StackPanel>
    

答案 1 :(得分:0)

您需要通过处理CheckBox.CheckedCheckBox.Unchecked事件在代码中执行此操作,因为我认为您不能使用{{1}添加或删除Resources在XAML中。但是,properties of the SystemColors class是只读的,因此您无法直接设置它们。

我找到了一种方法,但这涉及从Trigger导入kkk方法,因此可能不适合虚假心。有关详细信息,请参阅pinvoke.net网站上的SetSysColors (user32)页面。从链接页面:

user32.dll