我有一个comboBox
项目是颜色的地方,我想设置默认的选定项目。
例如在运行时我想将红色设置为所选项目。
我怎样才能做到这一点?我尝试设置SelectedItem
,SelectedValue
但没有运气它们不起作用,我是 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()
返回 a PropertyInfo[]
,而不是Color
实例集合。
添加它以将其转换为颜色的 IEnumerable:
ComboColor.ItemsSource = typeof(Colors)
.GetProperties()
.Select(p => p.GetValue(null));
要在 XAML 中使用颜色集合而不是 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>
但是,此解决方案会丢失颜色名称,并且 ComboBox 将仅显示 #AARRGGBB 值。
创建自己的 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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句