如何在WPF中绘制一个可点击的矩形 [英] How to draw a clickable rectangle in WPF

查看:522
本文介绍了如何在WPF中绘制一个可点击的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF应用程序的绝对初学者,需要一些帮助。所有我想要做的是从A点到B点绘制一个矩形,可以检测矩形被点击的时间。所以当它被点击时,它变成黄色,再次点击时,红色。

解决方案

有多种方法可以做到这一点。


  1. 将一个点击处理程序添加到矩形中,并从
  2. 之后的代码中切换颜色
  3. 绑定矩形的颜色到一个View Model属性,并使用Delegate Command设置点击的属性。

如果刚刚开始,第一个是最简单的使用XAML(尽管如果您想遵守MVVM,建议使用#2)。

 < Rectangle x:Name =rect 
Width =100Height =100Fill =Aquamarine
MouseLeftButtonDown =Rectangle_MouseLeftButtonDown/>

代码隐藏处理程序:

  bool toggle = false; 

private void Rectangle_MouseLeftButtonDown(object sender,MouseButtonEventArgs e)
{
rect.Fill = new SolidColorBrush(toggle?Colors.Aquamarine:Colors.DarkRed);
toggle =!toggle;
}


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.

  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;
 }

这篇关于如何在WPF中绘制一个可点击的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆