简体   繁体   中英

WPF - how to handle mouse events outside component which raised that event?

Context:

There's an application where you draw things on canvas. Where user clicks there's a black dot, for example. But handling that events raised by canvas in event handlers in main window code is just ugly for me. So I wrote a class which methods mirror canvas mouse events and I call those methods inside event handler.

public partial class Window1 : Window
{
    DrawingTool drawTool = new DrawingTool();
    public Window1()
    {
        InitializeComponent();            
    }

    private void drawingCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        drawTool.OnMouseLeftButtonDown(e);
    }
}

Nice, but I want more...

Question:

Is it possible to handle events raised by canvas in my DrawingTool class directly without having defined canvas event handlers. I'd like to keep my Window1 code clean and focused on window stuff and move events handling completely into my classes.

I thought about deriving DrawingTool from FrameworkElement, override OnRender and draw it transparently over the canvas so user's click seemed to be made on canvas but in fact would be raised in DrawingTool and handled internally. This approach works with drawing functionality (after drawing is done drawn object is added to canvas children and removed from DrawingTool children) but when it comes to selection mode or others there are problems with hit testing of elements for example.

So, I'll be grateful for any suggestion how to solve my problem or explanation why this is a stupid idea at all :)

只需将私有控件字段公开为公共属性,当您拥有Window1的实例时,就可以

Window1.DrawingCanvas.MouseLeftButtonDown += YourHandlerMethod;

I'm not sure whether I got your problem right, and I've only played with WPF a little, but how about creating a user control that contains your canvas and handling the mouse and drawing there? This could be named DrawingControl or the like.

That way you'd be able to have the drawing code contained in the class that represents the control. You might want to give the new user control a property that allows access to the "internal" canvas.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM