我的Combobox只有3个项目:Planing,Progress和Done,
<ComboBox SelectedIndex="0>
<ComboBoxItem Content="Planing"/>
<ComboBoxItem Content="Progress"/>
<ComboBoxItem Content="Done"/>
</ComboBox>
我如何更改ComboBox的背景颜色(由defult Gradiant设计)取决于选择了哪个项目.
例如:紫色表示“ Planing”,蓝色表示“ Progress”,绿色表示“ 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中使用DataTriggers
也可以通过在Style上设置多个DataTrigger来通过xaml完成.
<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.