Reputation: 11
txtbKleuren.Foreground = new SolidColorBrush(Color.FromArgb(100, 255, 125, 35)); I have 4 buttons with the names red, green, blue and yellow and a textblock. So when the color yellow comes on the textblock I have to press button yellow to get a point. How can i make the textblock randomly giving one of the 4 colors?
This is my code:
public MainPage()
{
this.InitializeComponent();
Random rand = new Random();
txtbKleuren.Foreground = new SolidColorBrush(Color.FromArgb(100, 255, 125, 35));
}
private void btnKleur4_Click(object sender, RoutedEventArgs e)
{
}
I don't know how to give a random color to the textbox so i just tried something! Please help me out. I really want to know it! And sorry for my bad Englisch.
Upvotes: 0
Views: 784
Reputation: 6251
First, I would recommend that you declare your Random
variable as a class member variable, so that you can access it later, if you need it. It is a good practice to do it this way. So, put it outside any methods/functions:
Random rand = new Random();
Coming on to the question, you can first declare an array of the predefined colors (Red, Blue, Green and Yellow):
Color[] colors = new Color[]
{
Colors.Red,
Colors.Blue,
Colors.Green,
Colors.Yellow
};
Instead of using Colors.Yellow
, etc. you can also define custom shades as you did in your question.
Next, use your rand
variable to generate a random number (between 0 and 3) to use as an index for the array:
int randIndex = rand.Next(0, 4); // 0, 3 + 1 -> the Random.Next() function's upper bound is exclusive.
Finally, get your random color:
Color randColor = colors[randIndex];
txtbKleuren.Foreground = new SolidColorBrush(randColor);
Or, you can even show both the name of the color and the corresponding Foreground color:
Dictionary<string, Color> colors = new Dictionary<string, Color>()
{
{
"Red",
Colors.Red
},
{
"Blue",
Colors.Blue
},
{
"Green",
Colors.Green
},
{
"Yellow",
Colors.Yellow
}
};
var randColName = colors.ToArray()[randIndex];
txtbKleuren.Text = randColName.Key;
txtbKleuren.Foreground = new SolidColorBrush(randColName.Value);
Upvotes: 1