WPF hit rectangular area test
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.
source to share
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" />
source to share