c# - 不同选定项目的 WPF 组合框背景

标签 c# wpf combobox styles

我的组合框只有 3 个项目:计划、进度和完成,

<ComboBox SelectedIndex="0>
    <ComboBoxItem Content="Planing"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>

如何根据选择的项目更改 ComboBox 的背景颜色(默认为渐变色)。

例如:紫色表示计划,蓝色表示进度,绿色表示完成。

注意:我指的是组合框背景,而不是组合框项目列表。

谢谢

最佳答案

1) 使用 selectionChanged 事件

您可以在 comboBox_SelectionChanged 事件中设置它

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (comboBox.SelectedItem.ToString() == "Planning")
    {
        comboBox.Background = Brushes.Purple;
    }
    else if (comboBox.SelectedItem.ToString() == "Progress")
    {
        comboBox.Background = Brushes.Blue;
    }
    else if (comboBox.SelectedItem.ToString() == "Done")
    {
        comboBox.Background = Brushes.Green;
    }
}

comboBox_SelectionChanged 事件将在每次更改组合框中的选定值时调用。在其中,您可以简单地验证所选项目的值并应用您想要的颜色。

这将是 Combobox

的 xaml
<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged"/>

2) 在 XAML 中使用数据触发器

它也可以通过在 Style.Triggers 上设置多个 DataTrigger 来完成,就像这样

<ComboBox x:Name="mycombobox">
    <ComboBox.Style>
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Planning">
                    <Setter Property="Background" Value="Purple" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Progress">
                    <Setter Property="Background" Value="Blue" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Done">
                    <Setter Property="Background" Value="Green" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
    <ComboBoxItem Content="Planning"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>

More information on DataTriggers:

Represents a trigger that applies property values or performs actions when the bound data meets a specified condition.

关于c# - 不同选定项目的 WPF 组合框背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43123419/

相关文章:

WPF 按钮样式

javascript - Ext JS 4.2 分页组合 - 如何跳到页面

html - 具有值和 ID 的 Vaadin ComboBox

c# - 在 C# Windows 窗体中更改动态创建的工具提示字体的简单方法?

c# - 如何从 ComboBox 控件获取 ToggleButton

c# - 属性/方法内联和对反射的影响

ms-access - 将 Microsoft Access 组合框中的默认值设置为当前月份

c# - 以编程方式添加数据注释

c# - 您如何正确测试 MVVM 中的 View ?

c# - WPF 项目控制 : Can't seem to get items to display in the view