我的组合框只有 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
<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/