Search code examples
c#windows-8microsoft-metro

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/


Solution

  • <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.