C# -how to add all system.drwaing.color items in a

2020-04-09 06:27发布

问题:

I'm trying to fill my list with system.drwaing.color items to pick a random color and set it to backColor.

Here is my code:

    List<Color> myList = new List<Color>();
    //rc.Add(Color.Chartreuse);
    //rc.Add(Color.DeepSkyBlue);
    //rc.Add(Color.MediumPurple);
    foreach (Color clr in System.Drawing.Color)
    {
      //error  
    }
    Random random = new Random();
    Color color = myList[random.Next(myList.Count - 1)];
    this.BackColor = color;

Error: 'System.Drawing.Color' is a 'type', which is not valid in the given context

Can anyone give me a Hand?

回答1:

public static List<Color> ColorStructToList()
{
    return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public)
                        .Select(c => (Color)c.GetValue(null, null))
                        .ToList();
}

List<Color> colorList = ColorStructToList();


private void randomBackgroundColorButton_Click(object sender, EventArgs e)
{
    List<Color> myList = ColorStructToList();
    Random random = new Random();
    Color color = myList[random.Next(myList.Count - 1)];
    this.BackColor = color;
}

public static List<Color> ColorStructToList()
{
    return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public)
                        .Select(c => (Color)c.GetValue(null, null))
                        .ToList();
}


回答2:

From this question:

string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));


回答3:

Here is your code:

private List<Color> GetAllColors()
{
    List<Color> allColors = new List<Color>();

    foreach (PropertyInfo property in typeof(Color).GetProperties())
    {
        if (property.PropertyType == typeof(Color))
        {
            allColors.Add((Color)property.GetValue(null));
        }
    }

    return allColors;
}


回答4:

Based on Artxzta's answer, in VB.net:

Imports System.Reflection

Dim allColors As New List(Of String)

For Each [property] As PropertyInfo In GetType(Colors).GetProperties()
        allColors.Add([property].Name)
Next


回答5:

My scenario is the follow and i hope somebody to find it useful:

I have a ComboBox control in a wpf window that i want to display all the colors from the Brushes class.

MainWindow.xaml

In the window declaration i have add the follow reference:

 xmlns:converters="clr-namespace:MyProjectName.Converters"

In the Window.Resources section i have register the converter with the "ColorConverter" name:

 <converters:StringToColorConverter x:Key="ColorConverter"/>

And somewhere in my xaml code i have implement the follow combobox:

<ComboBox Grid.Column="1" Grid.Row="3" ItemsSource="{Binding VBColors}"
 Margin="5,5,0,5" HorizontalContentAlignment="Stretch">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Rectangle Height="20" Fill="{Binding Path=., Converter={StaticResource ColorConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

MainWindow.cs

 private List<string> _vbColors =  typeof(Brushes).GetProperties().Select(x => x.Name).ToList();
 public List<string> VBColors
 { get { return _vbColors; } }

StringToColorsConverter.cs

    [ValueConversion(typeof(bool), typeof(SolidColorBrush))]
    public sealed class StringToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var stringValue = (string)value;
            SolidColorBrush solidColor = (SolidColorBrush)new BrushConverter().ConvertFromString(stringValue);
            return solidColor;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Some tips....

In the ComboBox.ItemTemplate binding you will find the binding to "Binding Path=." =>Since the colors list is not an object list but a list of strings,Binding Path=. is the way to bind the control to the string name

Also... Set te ComboBox HorizontalContentAlignment="Stretch" for streaching the Rectangle to the ComboBox width...try it to see the difference.

Keep coding, JJ