Click here to Skip to main content
14,550,550 members
Rate this:
Please Sign up or sign in to vote.
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.

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

Rate this:
Please Sign up or sign in to vote.

Solution 1

If you want a random colour from a collection, then just generate a random index into the collection:
int count = theCollection.Count;
Random r = new Random();
var randomValue = theCollection[r.Next(0, count)];
// You now have a random element from the collection
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100