I am an absolute beginner to WPF applications and need some help. All I’m trying to do is draw a rectangle from point A to point B, and be able to detect when the rectangle is clicked. So when it is clicked it turns yellow and when clicked again, red.
There are multiple ways to do this.
The first is easiest if you're just starting with XAML (although #2 is recommended if you want to adhere to MVVM).
<Rectangle x:Name="rect"
Width="100" Height="100" Fill="Aquamarine"
MouseLeftButtonDown="Rectangle_MouseLeftButtonDown" />
And the code-behind handler:
bool toggle = false;
private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
rect.Fill = new SolidColorBrush(toggle ? Colors.Aquamarine : Colors.DarkRed);
toggle = !toggle;
}
Use the Rectangle
control.
<Rectangle
Height="100"
Width="100"
MouseLeftButtonUp="Rectangle_MouseLeftButtonUp_1"
where Rectangle_MouseLeftButtonUp_1
is an event handler on the containing class.
Just be aware that unless the Rectangle has a background, you'll have to click the border. The background can be white, but it does need to be specified if it's to be clickable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With