Search code examples
c#wpfvisual-tree

How does one increase the hit testing radius on a rectangle in WPF?


Let's say I have a rectangle like this:

<Rectangle Grid.Column="1"
           Stroke="Red"
           StrokeDashArray="4.0 4.0"
           StrokeThickness="{Binding Path=CurrentThickness}"
           Visibility="{Binding Path=VisibleRectangle,
                                Converter={StaticResource VisibilityConverter}}"
           MouseUp="HandleMouseUp" />

This works for doing hit testing on the rectangle itself for the MouseUp event. However, the typical width of the rectangle is 1px wide, making clicking on the edge of the rectangle difficult. I would like to make the "effective click border size" for the Rectangle's stroke to be larger than the visual appearance of that stroke. (For instance, let's say the rectangle is drawn as 1px wide, but the mouse click region is actually 3px wide)

Is such a thing possible, or am I forced to increase the thickness of the Rectangle's stroke?


Solution

  • Hacky solution:

    put a "transparent" rectangle in the same place, and make your rectangle IsHitTestVisible="False"

    <Rectangle x:Name="Clickable"
               Grid.Column="1"
               MouseUp="HandleMouseUp"
               Fill="Transparent"/>
    
    <Rectangle Grid.Column="1"
               Stroke="Red"
               StrokeDashArray="4.0 4.0"
               StrokeThickness="{Binding Path=CurrentThickness}"
               IsHitTestVisible="False"
               Visibility="{Binding Path=VisibleRectangle,
                                    Converter={StaticResource VisibilityConverter}}"/>