如何在 WPF 中绘制可点击的矩形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13484423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:18:43  来源:igfitidea点击:

How to draw a clickable rectangle in WPF

c#wpfeventsxaml

提问by FrostyFire

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, andbe able to detect when the rectangle is clicked. So when it is clicked it turns yellow and when clicked again, red.

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

回答by McGarnagle

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.
  1. 向矩形添加单击处理程序,并从后面的代码切换其颜色
  2. 将矩形的颜色绑定到视图模型属性,并在单击时使用委托命令设置属性。

The first is easiest if you're just starting with XAML (although #2 is recommended if you want to adhere to MVVM).

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

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

回答by Kirk Broadhurst

Use the Rectanglecontrol.

使用Rectangle控件。

<Rectangle
    Height="100"
    Width="100"
    MouseLeftButtonUp="Rectangle_MouseLeftButtonUp_1"

where Rectangle_MouseLeftButtonUp_1is an event handler on the containing class.

其中Rectangle_MouseLeftButtonUp_1是包含类的事件处理程序。

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.

请注意,除非矩形有背景,否则您必须单击边框。背景可以是白色的,但如果它是可点击的,则需要指定它。