Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Adorner Hit Testing / MouseDown Event

Tags:

c#

wpf

adorner

I have an Adorner which adornes a Border (please see screenshot below). The MouseDown Event for the Adorner is however only raised, when clicking on an element in the adorner. I need the MouseDown Event to be raised, when clicking on any place in the adorner above the adorned element. How can this be done? Do I have to add an transparent control in the adorner or is there another way for this? Thanks for any help!

Screenshot and VS 2008 Project: http://cid-0432ee4cfe9c26a0.skydrive.live.com/browse.aspx/%C3%96ffentlich?uc=2

The Code for the adorner:

class myAdorner : Adorner
{
    public myAdorner(UIElement element)
        : base(element)
    {
        this.MouseDown += new System.Windows.Input.MouseButtonEventHandler(myAdorner_MouseDown);
    }


    void myAdorner_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        MessageBox.Show("ok");
    }


    // Draws two rectangles: one in the upper-left and another one in the lower-right corner
    protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
    {
        Size size = this.AdornedElement.RenderSize;

        Rect r1 = new Rect(0.5, 0.5, 20, 20);
        Rect r4 = new Rect(size.Width - 20.5, size.Height - 20.5, 20, 20);


        SolidColorBrush brush = new SolidColorBrush(Colors.AliceBlue);
        Pen pen = new Pen(Brushes.Black, 1);

        drawingContext.DrawRectangle(brush, pen, r1);
        drawingContext.DrawRectangle(brush, pen, r4);
    }
}
like image 408
stefan.at.wpf Avatar asked Mar 29 '10 01:03

stefan.at.wpf


2 Answers

When I've done this in the past, I've always used a transparent container. It's not enough to have a null Brush; you actually need to use color #00000000 (or some other alpha 0 color). You can turn off IsHitTestVisible for the elements inside the container so that the container will receive all of the mouse down events.

like image 161
Dan Bryant Avatar answered Nov 13 '22 03:11

Dan Bryant


So the problem is that your adorner only can raise mouse events where there are visible elements in your adorner...the two squares in the corner.

If you want to listen for mouseevents throughout the element you're adorning you should register AdornedElement.PreviewMouseDown This will give your adorner a chance to do its work before the MouseDown event is fired by the adorned element.

like image 45
Michael Brown Avatar answered Nov 13 '22 02:11

Michael Brown