-3

I need some help. I'm developing this software, which I want to have some ComboBoxItems in a ComboBox which has a name and a color sample. Kinda look like when u do like this:

cmbColors.ItemsSource = typeof(Colors).GetProperties();

Which will be like this: Picture

Basically, the only thing I need, is to add my own RGB based (+Name) Colors to my Combobox

  • Where is the rest of your code, if you have none, see this question https://stackoverflow.com/questions/29263904/wpf-combobox-as-system-windows-media-colors – TheGeneral Sep 22 '18 at 08:52

1 Answers1

0

First you need to create a Color view model

public class ColorViewModel : INotifyPropertyChanged
{
    public string _name;
    public Color _color;

    public ColorViewModel(string name, Color color)
    {
        this._name = name;
        this._color = color;
    }

    public string Name
    {
        get => this._name;
        set
        {
            if (value == this._name) return;
            this._name = value;
            this.OnPropertyChanged();
        }
    }


    public Color Color
    {
        get => this._color;
        set
        {
            if (value == this._color) return;
            this._color = value;
            this.OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Then, your view's viewmodel could contain a list of all your colors. You can either fetch them from a list you have made, or get the ones that are built in .net.

public class ViewModel
{
    public ViewModel()
    {
        var allColors = typeof(Colors).GetProperties();
        foreach(var colorInfo in allColors)
        {
            this.Colors.Add(new ColorViewModel(colorInfo.Name, (Color)colorInfo.GetValue(null)));
        }
    }

    public ObservableCollection<ColorViewModel> Colors { get; } = new ObservableCollection<ColorViewModel>();

}

Finally, your xaml could look like this

    <ComboBox ItemsSource="{Binding Colors}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Rectangle Height="20" Width="20" >
                        <Rectangle.Fill>
                            <SolidColorBrush Color="{Binding Color}" />
                        </Rectangle.Fill>
                    </Rectangle>
                    <TextBlock Margin="10,0,0,0" Text="{Binding Name}" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

It should look like this in your application It should look like this in your application