Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a clickable rectangle in WPF

Tags:

c#

events

wpf

xaml

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.

like image 796
FrostyFire Avatar asked Oct 20 '25 11:10

FrostyFire


2 Answers

There are multiple ways to do this.

  1. Add a click handler to the rectangle, and toggle its color from code behind
  2. 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;
 }
like image 168
McGarnagle Avatar answered Oct 22 '25 23:10

McGarnagle


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.

like image 28
Kirk Broadhurst Avatar answered Oct 23 '25 01:10

Kirk Broadhurst