Search code examples
c#wpfadorner

WPF: Adorner Hit Testing / MouseDown Event


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

Solution

  • 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.