Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a way to randomly get colors from a collection System.Windows.Media.Brushes or System.Windows.Media.Colors. I'm interested in getting a pair - (color name, color).

P.S. I know about the way to get a random color without a name.

C#
Random r = new Random();
Brush brush = new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255), (byte)r.Next(1, 255), (byte)r.Next(1, 233)));


What I have tried:

I'm looking for a way to get a random color from a collection System.Windows.Media.Brushes or System.Windows.Media.Colors.
Posted
Updated 22-May-20 22:29pm

1 solution

If you want a random colour from a collection, then just generate a random index into the collection:
C#
int count = theCollection.Count;
Random r = new Random();
var randomValue = theCollection[r.Next(0, count)];
// You now have a random element from the collection
 
Share this answer
 
Comments
Member 12618031 23-May-20 4:44am    
System.Windows.Media.Brushes is a standard collection and it does not support methods .Count and [r.Next(0, count)]. I do not know why. Perhaps I need to create my own collection with color names.
phil.o 23-May-20 4:56am    
System.Windows.Media.Brushes is not a collection, i.e. it does not implement basic collection interfaces. In this case, you'd better create your own collection. A possible choice would be a Dictionary<string, Color> mapping the colour-name to its colour-value. Another possible choice would be a List<Tuple<string, Color>>.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900