我找不到问题的解决方案有困难,即我有一个想法,根据区域为不同颜色的组合框的每一行/每列着色,但我找不到任何线索或提示或说明这样做。该应用程序非常简单
<ComboBox x:Name="comboBox1" HorizontalAlignment="Left" Margin="84,70,0,0" VerticalAlignment="Top" Width="230"/>
这是我的XAML组合框,我从代码填写:
SortedList<int, string> AreaList = new SortedList<int, string>();
AreaList.Add(1, "Agriculture");
AreaList.Add(2, "Forestry");
AreaList.Add(3, "Fruits");
AreaList.Add(4, "Food");
AreaList.Add(5, "Metals");
AreaList.Add(6, "Mining");
AreaList.Add(7, "Electricity");
AreaList.Add(8, "Building Contracts");
AreaList.Add(9, "Transport");
AreaList.Add(10, "Alcohol");
AreaList.Add(11, "Information Technologies");
AreaList.Add(12, "Health And Social Services");
AreaList.Add(13, "Art and Entertainement");
AreaList.Add(14, "Hospitality Business");
AreaList.Add(15, "Education");
AreaList.Add(16, "Real Estate");
AreaList.Add(17, "Sales");
AreaList.Add(18, "Architecture");
AreaList.Add(19, "Engineering");
AreaList.Add(20, "Wholesale");
AreaList.Add(21, "Other");
comboBox1.ItemsSource = AreaList.ToList();
comboBox1.SelectedValuePath = "Key";
comboBox1.DisplayMemberPath = "Value";
这些项目中的每一个都在另一个窗口中显示颜色,但我想在组合框中显示这些颜色,即&#34;农业&#34;行/列应为绿色等。 有没有解决方案,还是我必须重做它?
答案 0 :(得分:0)
您可以使用ItemContainerStyle和Converter
public class StringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (((KeyValuePair<int, string>)value).Value.ToString() == "Agriculture")
return Brushes.Green;
//and so on or other ways to get the color
return Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
和XAML如下,
<Window.Resources>
<local:StringToColorConverter x:Key="StringToColorConverter"/>
</Window.Resources>
<Grid >
<ComboBox x:Name="comboBox1" HorizontalAlignment="Left" Margin="84,70,0,0" VerticalAlignment="Top" Width="230">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Background" Value="{Binding Converter={StaticResource StringToColorConverter}}">
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</Grid>
答案 1 :(得分:0)
对于映射到颜色的每个值,您可以将ItemContainerStyle与DataTrigger一起使用:
<ComboBox x:Name="comboBox1">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Value}" Value="Agriculture">
<Setter Property="Background" Value="Green" />
</DataTrigger>
<DataTrigger Binding="{Binding Value}" Value="Forestry">
<Setter Property="Background" Value="Red" />
</DataTrigger>
<!-- and so on-->
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
您可能还想阅读此内容:
在WPF中更改ComboBox的背景颜色: https://blog.magnusmontin.net/2014/04/30/changing-the-background-colour-of-a-combobox-in-wpf-on-windows-8/