从WPF中的Drawingcontext绘制的矩形或椭圆形的鼠标单击事件 [英] Mouse click events for Rectangle or ellipse drawn from Drawingcontext in WPF

查看:771
本文介绍了从WPF中的Drawingcontext绘制的矩形或椭圆形的鼠标单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我们如何编写从自定义画布OnRender方法绘制的矩形,椭圆形,路径几何等形状的Mouseleftclick或mouseRight单击事件.

我在WPF窗口上有一个自定义画布.在画布上,通过鼠标事件,我绘制了形状.现在,我想为形状生成点击事件.

代码:

Hi,

How can we write Mouseleftclick or mouseRight click events for the shapes like rectangles,ellipse,pathgeometry etc. which are drawn from custom canvas OnRender method.

I have a custom canvas on the WPF window. on the canvas with the mouse events i have drawn shapes. Now i want to generate click events for the shapes.

code:

protected override void OnRender(DrawingContext dc)
{
SolidColorBrush myBrush = new SolidColorBrush(Colors.Transparent);
Pen mypen=new Pen(Brushes.Black,1);			
Rect myrect=new Rect (0,0,this.Width,this.Height);  
dc.DrawRectangle(new SolidColorBrush(Colors.White),new Pen(Brushes.Black,1),myrect);
 
// Draw ellipse
  if(Shapetype=="Ellipse")
{                        dc.DrawEllipse(myBrush,mypen,Position,Shapewidth,Shapeheight); 
 }
// Draw Rectangle
    if(Shapetype=="Rectangle")
     {
    Rect rect1=new Rect(startPoint.X,startPoint.Y,Shapewidth,Shapeheight);  
      dc.DrawRectangle(myBrush,mypen,rect1);

     }
}



我可以在此处在画布上绘制矩形,椭圆形,当我单击在画布上呈现的矩形或椭圆形形状时,如何生成鼠标单击事件.


非常感谢提供示例帮助..!



Here iam able to draw rectangle, ellipse on the canvas, how can i generate mouse click events when i click on rectangle or ellipse shapes rendered on canvas.


Any help with an example is much appreciated..!

推荐答案

鼠标事件在 Shape (例如椭圆路径等...).

The mouse events are declared in the UIElement class. When we want interactive shapes in the UI we usually put elements that derive from Shape (e.g. Ellipse, Rectangle, Path etc...).

如果要交互式形状,可以创建Shape并将其添加到

If you want an interactive shape, you can create a Shape and add it to the Children of the Canvas, as the following:

Ellipse el = new Ellipse
{
    Width = 100,
    Height = 50,
    Fill = Brushes.Green
};
Canvas.SetTop(el, 30);
Canvas.SetLeft(el, 40);
myCanvas.Children.Add(el);

然后您可以创建事件处理程序:

Then you can create the event-handler:

void OnEllipseMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    // ...
}

,然后注册形状的事件:

and, register to the shape''s event:

el.MouseLeftButtonDown += OnEllipseMouseLeftButtonDown;

如果要处理使用DrawingContext绘制的形状的事件,可以存储形状的详细信息(如边界矩形),并在Canvas的事件处理程序中使用这些详细信息事件,以查找单击的形状.

If you want to handle events for shapes that is drawn using DrawingContext, you can store the details of the shapes (like bounding rectangle) and, use these details in the event-handlers of the Canvas''s events, in order to find which shape is clicked.


这篇关于从WPF中的Drawingcontext绘制的矩形或椭圆形的鼠标单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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