ManIkWeet
ManIkWeet

Reputation: 1338

WPF - HitTest radius around Polyline/Path

I have a thin 1px wide line on a canvas, I want an area around the line (eg 5 pixels wide) to be hit testable.

<Polyline Points="10,10,50,50,90,10,130,50,170,10,210,50,250,10" StrokeThickness="1">
  <Polyline.Style>
    <Style TargetType="Polyline">
      <Setter Property="Stroke" Value="Magenta"/>
      <Setter Property="StrokeThickness" Value="1"/>
      <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Stroke" Value="Blue" />
        </Trigger>
    </Style.Triggers>
    </Style>
  </Polyline.Style>
</Polyline>

Example code above has a difficult to hit polyline.
I don't want to add a Border around the polyline (Makes all areas inside the line hittable).
Setting the Fill property doesn't work for straight lines and makes (some) areas inside the line hittable...

Upvotes: 2

Views: 323

Answers (1)

Mitya
Mitya

Reputation: 642

Not the best but working solution. Create a copy of your polyline with bigger StrokeThickness value and Transparent Stroke colour. In original Polyline add DataTrigger to catch IsMouseOver property changes of new invisible Polyline

<Canvas>
    <Polyline x:Name="HitTestPolyline" Points="10,10,50,50,90,10,130,50,170,10,210,50,250,10" Stroke="Transparent" StrokeThickness="5"/>
    <Polyline Points="10,10,50,50,90,10,130,50,170,10,210,50,250,10" StrokeThickness="1">
        <Polyline.Style>
            <Style TargetType="Polyline">
                <Setter Property="Stroke" Value="Magenta"/>
                <Setter Property="StrokeThickness" Value="1"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=HitTestPolyline, Path=IsMouseOver}" Value="True">
                        <Setter Property="Stroke" Value="Blue" />
                    </DataTrigger>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Stroke" Value="Blue" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Polyline.Style>
    </Polyline>
</Canvas>

Note that original Trigger should not be removed.

Upvotes: 1

Related Questions