Search code examples
c#formsdictionarycomboboxbrush

Easy way to enumerate class properties and then specify that property


I have a windows form and I want the user to specify the colour of a brush system.drawing.brush and then my app to consume this natively. There are loads of brush colours and I was wondering if it was possible to enumerate all the possible colour combinations?

I could then populate the combobox with them. THEN the second part would be to specify the brush property programmatically without having to do a lookup table.


Solution

  • For a list of Color names you can use Reflection:

    Type colorType = typeof(System.Drawing.Color);
    
    PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
    
    var colorNames = propInfoList.Select(c => c.Name);
    

    Use that list to populate your Combobox

    Then, once user selects the Color, you can create a brush using the following:

    var brushColor = Color.FromName(selectedColorFromCombo);
    
    var brush = new SolidBrush(brushColor);