E
E
egorka23852019-06-04 22:23:12
WPF
egorka2385, 2019-06-04 22:23:12

How to make a random color by clicking on the Button and have the Rectangle change color?

by clicking on the Button, you need the Rectangle to change color randomly in C # (wpf)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LiptonOlolo, 2019-06-04
@LiptonOlolo

Let's take this window as an example:

<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>

Let's declare 2 variables in the window class:
private List<SolidColorBrush> brushes;
private Random rnd;

We initialize in the constructor:
public MainWindow()
{
  InitializeComponent();

  rnd = new Random();
  brushes = new List<SolidColorBrush> //заполняем цвета, которые будет принимать Rectangle
  {
    Brushes.AliceBlue,
    Brushes.AntiqueWhite,
    Brushes.Aqua,
    Brushes.Aquamarine
  };
}

And finally the button code:
private void Button_Click(object sender, RoutedEventArgs e)
{
  MyRectangle.Fill = brushes[rnd.Next(0, brushes.Count)];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question