我想构建简单的 ColorComboBox,但我不知道, 如何使用 C# 在通用 Windows 平台中获取系统颜色 (KnownColors)。 类型 KnownColors 不可访问。
最佳答案
Windows.UI.Colors类具有从 AliceBlue 到 YellowGreen 的已知颜色的属性。如果您想要这些颜色的列表,您可以使用反射遍历属性名称来构建您自己的列表以进行绑定(bind)。
例如:
保存颜色信息的类
public class NamedColor
{
public string Name { get; set; }
public Color Color { get; set; }
}
以及要绑定(bind)的属性:
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 绑定(bind)到颜色集合:
<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>
关于c# - 如何在uwp中获取系统颜色列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103787/