#963 – A Color Selection Box Organized by Hue, part II

In part I, I included source code for generating a list of sample colors.

To bind to a generated color list, we can call ColorUtil.GenerateColorList and make the result available via a property.  In the code sample below, we generate a list of 4,096 colors (16 values for red, green and blue).

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        this.InitializeComponent();
        this.DataContext = this;

         ColorList = ColorUtil.GenerateColorList(16);
    }

    private List<ColorWithInfo> colorList;
    public List<ColorWithInfo> ColorList
    {
        get { return colorList; }
        protected set
        {
            colorList = value;
            RaisePropertyChanged("ColorList");
        }
    }

    // INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void RaisePropertyChanged(string propName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

In our XAML, we can create a simple ComboBox that binds to this list.  We set the ItemTemplate to display each color as a simple rectangle and the ItemsPanel as a WrapPanel with a fixed width.

    <ComboBox Margin="15" Height="30" Width="200"
                ItemsSource="{Binding ColorList}"
                ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Rectangle Height="55" Width="55">
                        <Rectangle.Fill>
                            <SolidColorBrush Color="{Binding Color}"/>
                        </Rectangle.Fill>
                    </Rectangle>
                </Grid>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <ComboBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True" Orientation="Horizontal" Width="1000"/>
            </ItemsPanelTemplate>
        </ComboBox.ItemsPanel>
    </ComboBox>

Below is an image showing the ComboBox in action. Note that the colors are sorted by hue, given that the GenerateColorList method sorted the color values this way.

963-001

Advertisement