Hit testing WPF UserControl

Recently I work an application, which needs to display data from various kinds of controls. Most of them can be derived from seven base types. For the sheer amount of data that are available, I let the end user to decide which one of them wants to examine in the user interface. So basically the user can drag controls from a list to a WrapPanel, which will organize them, and start to show the current states or values. To provide ability to remove them, I use the WrapPanel’s ContextMenu Delete function. Inside Delete’s event I examine the HitTestResult to decide which control should I remove.
Hit testing proves itself a kind of beast. Usually it always returned the particular item, which is the top most at the hit location. No matter that I set the controls IsHitTestEnabled property to false. The MSDN Library suggested a solution: override the HitTestCore implementation, but that won’t work either. Finally, was able to figure out, how get the proper control, that need to be removed.
Simply I walk through the visual tree, and if I get something desirable, than I’m done…

 HitTestResult res = VisualTreeHelper.HitTest (wpControlHost, e.GetPosition (wpControlHost));
            UIElement removeItem = null;
            if (res != null)
                DependencyObject obj = VisualTreeHelper.GetParent (res.VisualHit);
                int toolId = -1;
                while (obj != null)
                    if (obj is UserControl)
                        toolId = (int)obj.GetType ().GetProperty ("ToolId").GetValue (obj, null);

                        // you can examine further the type of the usercontrol
                        if (obj is PressureControl)
                            System.Diagnostics.Debug.WriteLine ("is pressure control");

                        if (obj is CompressorControl)
                            System.Diagnostics.Debug.WriteLine ("is compressor control");

                        removeItem = obj as UIElement;
                        obj = null;
                        obj = VisualTreeHelper.GetParent (obj);

                if (removeItem != null)
                    wpControlHost.Children.Remove (removeItem);

A little update:
Sometimes the HitTest simply fall through the whole VisualTree, to avoid these issues, add a transparent background for the UserControl, that will help.


One thought on “Hit testing WPF UserControl

  1. Simon says:

    Just came across this, helped me massively solve a problem I was having. Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s