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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.