我想构建简单的ColorComboBox,但我不知道, 如何使用c#在通用Windows平台中获取系统颜色(KnownColors)。 无法访问类型KnownColors。
答案 0 :(得分:7)
Windows.UI.Colors类具有AliceBlue到YellowGreen的已知颜色属性。如果你想要这些颜色的列表,你可以使用反射遍历属性名称来构建你自己的列表来绑定。
例如:
保存我们的颜色信息的类
public class NamedColor
{
public string Name { get; set; }
public Color Color { get; set; }
}
要绑定的属性:
public ObservableCollection<NamedColor> Colors { get; set; }
使用反射构建NamedColor列表:
foreach (var color in typeof(Colors).GetRuntimeProperties())
{
Colors.Add(new NamedColor() { Name = color.Name, Color = (Color)color.GetValue(null) });
}
和一些绑定到颜色集合的Xaml:
<ComboBox ItemsSource="{Binding Colors}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Rectangle Grid.Column="0" Height="30" Width="30" Margin="2" VerticalAlignment="Center" Stroke="{ThemeResource SystemControlForegroundBaseHighBrush }" StrokeThickness="1">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Color}" />
</Rectangle.Fill>
</Rectangle>
<TextBlock Text="{Binding Name}" Grid.Column="1" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>