Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of system colors in uwp

Tags:

c#

uwp

I would like to build simple ColorComboBox, but I don't know, how do I get system colors(KnownColors) in Universal Windows Platform with c#. Type KnownColors is not accessible.

like image 768
Ive Avatar asked Jan 07 '23 17:01

Ive


1 Answers

The Windows.UI.Colors class has properties for known colours from AliceBlue to YellowGreen. If you want a list of these colours you can use reflection to walk through the property names to build your own list to bind to.

For example:

A class to hold our color information

public class NamedColor
{
    public string Name { get; set; }
    public Color Color { get; set; }
}

And a property to bind to:

public ObservableCollection<NamedColor> Colors { get; set; }

Use reflection to build NamedColor list:

foreach (var color in typeof(Colors).GetRuntimeProperties())
{
    Colors.Add(new NamedColor() { Name = color.Name, Color = (Color)color.GetValue(null) });
}

And some Xaml to bind to the color collection:

<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>
like image 54
Rob Caplan - MSFT Avatar answered Jan 14 '23 15:01

Rob Caplan - MSFT