James L
James L

Reputation: 16854

WPF hit testing a rectangular area

I have a WrapPanel containing an arbitrary number of jagged sized elements. I'd like to implement drag select for my items.

It seems pretty obvious how to HitTest for a point, but how can I find all items within a rectangular area?

Upvotes: 3

Views: 2982

Answers (2)

Clemens
Clemens

Reputation: 128013

You may use VisualTreeHelper.HitTest with a GeometryHitTestParameters argument and a HitTestFilterCallback that checks if a Visual is a direct child of the Panel.

Something like this:

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 complicated, but the HitTestFilterCallback is necessary to get all Visuals in the visual tree, not only those that actually got hit. For example if your panel contains Label controls, the HitTestResultCallback will only be called for the Border and TextBlock child Visuals of each Label.

Upvotes: 6

Smaug
Smaug

Reputation: 2673

The option for controlling hit test visibility is the IsHitTestVisible property. This property allows you to control hit test visibility regardless of the brush with which the UIElement is rendered.

Also, You want to set the Fill to Transperent

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

Upvotes: -1

Related Questions