WPF hit rectangular area test

I have a WrapPanel containing an arbitrary number of jaggedly sized elements. I would like to implement drag and drop functionality for my elements.

Seems pretty obvious like HitTest for a point, but how can I find all the items in a rectangular area?

+3


source to share


2 answers


You can use VisualTreeHelper.HitTest with GeometryHitTestParameters and HitTestFilterCallback , which checks if Visual is a direct child of the panel.

Something like that:

var selectedElements = new List<DependencyObject>();

var rect = new RectangleGeometry(...);
var hitTestParams = new GeometryHitTestParameters(rect);

var resultCallback = new HitTestResultCallback(
    result => HitTestResultBehavior.Continue);

var filterCallback = new HitTestFilterCallback(
    element =>
    {
        if (VisualTreeHelper.GetParent(element) == panel)
        {
            selectedElements.Add(element);
        }
        return HitTestFilterBehavior.Continue;
    });

VisualTreeHelper.HitTest(
    panel, filterCallback, resultCallback, hitTestParams);

      




It looks a little more complicated, but HitTestFilterCallback

you need to get all the Visuals in the visual tree, not just the ones that actually hit. For example, if your panel contains Label controls, HitTestResultCallback

only Border and TextBlock children will be called. Visual images of each label.

+4


source


An option to control the visibility of a test case is a property IsHitTestVisible

. This property allows you to control the visibility of the test case regardless of the brush that the UIElement is rendered with.

Also, you want to install Fill to Transperent



 <Rectangle  Width="200" Height="200" Margin="170,23,12,35" Fill="Transparent" IsHitTestVisible="True"   />

      

-1


source







All Articles