How to draw a clickable rectangle in WPF
c#, events, wpf, xaml
Solution
There are multiple ways to do this.
- Add a click handler to the rectangle, and toggle its color from code behind
- Bind the rectangle's color to a View Model property, and set the property on click using a Delegate Command.
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;
}
Problem
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.