来自颜色的组合项目以编程方式WPF设置所选项目



我有一个comboBox,其中的项目是"颜色",我想设置默认选择的项目。

例如,在运行时,我想将红色设置为所选项目。

我怎样才能做到这一点?我试着设置了SelectedItemSelectedValue,但运气不好,它们不起作用,我是WPF的新手。

这是我的密码。

XAML

<ComboBox x:Name="ComboColor" Width="50" Height="50">
   <ComboBox.ItemTemplate>
      <DataTemplate>
         <StackPanel Orientation="Horizontal">
            <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2" />
            <TextBlock Text="{Binding Name}" />
         </StackPanel>
      </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>

C#代码隐藏

public MainWindow()
{
   InitializeComponent();
   ComboColor.ItemsSource = typeof(Colors).GetProperties();
   //not working
   ComboColor.SelectedItem = Colors.Red;
   //not working also
   ComboColor.SelectedValue = Colors.Red;
}

表达式

typeof(Colors).GetProperties()

返回一个PropertyInfo[],而不是Color实例的集合。

将其添加到颜色的IEnumerable中:

ComboColor.ItemsSource = typeof(Colors)
    .GetProperties()
    .Select(p => p.GetValue(null));

要在XAML中使用Colors集合而不是PropertyInfo,请将ItemTemplate更改为:

<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Rectangle Width="16" Height="16" Margin="0,2,5,2">
                <Rectangle.Fill>
                    <SolidColorBrush Color="{Binding}"/>
                </Rectangle.Fill>
            </Rectangle>
            <TextBlock Text="{Binding}" />
        </StackPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>

但是,此解决方案将丢失颜色名称,并且组合框将仅显示#AARGGBB值。


创建自己的ColorInfo类可能是有意义的

public class ColorInfo
{
    public ColorInfo(PropertyInfo info)
    {
        Name = info.Name;
        Color = (Color)info.GetValue(null);
    }
    public string Name { get; }
    public Color Color { get; }
}

像这样设置ItemsSource

ComboColor.ItemsSource = typeof(Colors).GetProperties()
    .Select(p => new ColorInfo(p));

并与结合

<Rectangle Width="16" Height="16" Margin="0,2,5,2">
    <Rectangle.Fill>
        <SolidColorBrush Color="{Binding Color}"/>
    </Rectangle.Fill>
</Rectangle>
<TextBlock Text="{Binding Name}" />

<ComboBox SelectedValuePath="Name" ...>

你可以写

ComboColor.SelectedValue = "Red";

<ComboBox SelectedValuePath="Color" ...>

这将起作用:

ComboColor.SelectedValue = Colors.Red;

您正在使用反射从类型Colors中的所有属性获取PropertyInfo实例。由于ItemsSourcePropertyInfo类型的集合,因此不能仅将Color指定为所选项目。事实上,所选项目必须等于ItemsSource中的相应实例

要使此操作按预期进行,请获取要选择的颜色的PropertyInfo实例。

ComboColor.SelectedItem = typeof(Colors).GetProperty(nameof(Colors.Red));

最新更新