Viral Jain
Viral Jain

Reputation: 1014

How to add colors to a combobox in metro app?

I want to add a list of colours to a combobox in metro app using C#. In turn, user can choose a particular colour from the list to change background.

The probable library available is Windows.UI.Colors

Here is a link to achieve it for a simple Desktop app: http://www.c-sharpcorner.com/uploadfile/mahesh/how-to-load-all-colors-in-a-combobox-using-C-Sharp/

But I was not able to port it to metro environment.

Also, both colour name as well as colour itself as a list item would be a huge plus.

Another thread from MSDN: http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/880a3b5b-e287-4cdc-a1ab-d1cd4a19aedb/

Upvotes: 2

Views: 1741

Answers (2)

Ross Dargan
Ross Dargan

Reputation: 6021

This code works for me:

var colorsTypeInfo = typeof(Colors).GetTypeInfo();
var properties = colorsTypeInfo.DeclaredProperties;
Dictionary<string, string> colours = new Dictionary<string, string>();
foreach (var dp in properties)
{
    colours.Add(dp.Name, dp.GetValue(typeof(Colors)).ToString());
}

Be sure you have added the following reference's otherwise it won't work

using System.Reflection;
using Windows.UI;

Upvotes: 3

Viral Jain
Viral Jain

Reputation: 1014

<ComboBox x:Name="cbColorNames" Grid.Row="1" Height="40"
      ItemsSource="{Binding Colors}"
      SelectedItem="{Binding SelectedColorName, Mode=TwoWay}">
<ComboBox.ItemTemplate>
    <DataTemplate>
        <Grid Background="Black">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Rectangle Width="35" Height="20" Fill="{Binding Name}" Margin="5,0"/>
            <TextBlock Grid.Column="1" Margin="10,0,0,0" Text="{Binding Name}" Foreground="White"/>
        </Grid>
    </DataTemplate>
</ComboBox.ItemTemplate>

This is the xaml file.

private static void LoadColors()
{
    var t = typeof(Colors);
    var ti = t.GetTypeInfo();
    var dp = ti.DeclaredProperties;
    colors = new List<PropertyInfo>();
    foreach (var item in dp)
    {
        colors.Add(item);
    }
}
private static List<PropertyInfo> colors;
public List<PropertyInfo> Colors
{
    get
    {
        if (colors == null)
            LoadColors();
        return colors;
    }
}

This is C# code.

Thanks all for support & help.

Upvotes: 2

Related Questions