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

2020-04-09 06:56发布

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?

5条回答
成全新的幸福
2楼-- · 2020-04-09 07:02

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

查看更多
贪生不怕死
3楼-- · 2020-04-09 07:03

From this question:

string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));
查看更多
淡お忘
4楼-- · 2020-04-09 07:04
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();
}
查看更多
劫难
5楼-- · 2020-04-09 07:04

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;
}
查看更多
Fickle 薄情
6楼-- · 2020-04-09 07:07

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
查看更多
登录 后发表回答