How to make a random color by clicking on the Button below the Rectangle and changed the colour?

pressing the Button should change to a Rectangle in a random color in C#(wpf)
March 23rd 20 at 19:06
1 answer
March 23rd 20 at 19:08
Take the example of this window:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>

 <Button Content="Change color"
Click="Button_Click"
Margin="15"/>

 <Rectangle Name="MyRectangle" 
 Grid.Row="1" 
Margin="15"
Fill="Red"/>
</Grid>


Declare 2 variables in the window class:
private List<SolidColorBrush> brushes;
private Random rnd;


Initialize in the constructor:
public MainWindow()
{
InitializeComponent();

 rnd = new Random();
 brushes = new List<SolidColorBrush> //fill in the colors that will make a Rectangle
{
Brushes.AliceBlue,
Brushes.AntiqueWhite,
Brushes.Aqua
Brushes.Aquamarine
};
}


And finally, the code of the button:
private void Button_Click(object sender, RoutedEventArgs e)
{
 MyRectangle.Fill = brushes[rnd.Next(0, brushes.Count)];
}
It is possible via reflection to get a list of all colors not to register independently - Antonio.Kunze0 commented on March 23rd 20 at 19:11
@Antonio.Kunze0, I have described the easiest option, I didn't say that this is the only - Ephraim83 commented on March 23rd 20 at 19:14

Find more questions by tags WPF