wpfapp.xamlrelativesourcevisualbrush

Access user control property in App.xaml style WPF


I'm trying to set the "Stroke" property of Path in my visual brush (Defined in App.xaml) via the property from my model. I'm using this style in my another control template in a usercontrol.

Style in User control resources:

<Ellipse x:Name="slideThumb" Height="25" Width="25" Stroke="{Binding ThumbColor, UpdateSourceTrigger=PropertyChanged}">
                        <Ellipse.Style>
                            <Style TargetType="{x:Type Ellipse}">
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding IsHatchBrush}" Value="true">
                                        <Setter Property="Fill" Value="{StaticResource HatchBrushVertical}" />
                                    </DataTrigger>
                                    <DataTrigger Binding="{Binding IsHatchBrush}" Value="false">
                                        <Setter Property="Fill" Value="{Binding ThumbColor, UpdateSourceTrigger=PropertyChanged}" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Ellipse.Style>
                    </Ellipse>

Brush Defined in App.xaml:

<VisualBrush x:Key="HatchBrushVertical" TileMode="Tile" Viewport="0,0,2,3" ViewportUnits="Absolute" Viewbox="0,0,5,5" ViewboxUnits="Absolute">
        <VisualBrush.Transform>
            <RotateTransform Angle="45" />
        </VisualBrush.Transform>
        <VisualBrush.Visual>
            <Canvas>
                <Path Data="M 0 0 L 0 10" Stroke="{Binding Path=Stroke, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Ellipse}}}" StrokeThickness="5"/>
            </Canvas>
        </VisualBrush.Visual>
    </VisualBrush>

Problem here is, I'm not able to set the Stroke property of the visal brush in app.xaml through the binding.

Need help. Thanks in advance


Solution

  • You may perhaps use the Brush as an OpacityMask.

    First, create a (simpler) DrawingBrush instead of a VisualBrush:

    <DrawingBrush x:Key="HatchBrush" TileMode="Tile"
                  Viewport="0,0,3,3" ViewportUnits="Absolute"
                  Viewbox="0,0,2,2" ViewboxUnits="Absolute">
        <DrawingBrush.Drawing>
            <GeometryDrawing Geometry="M-1,2 L2,-1 M0,3 L3,0">
                <GeometryDrawing.Pen>
                    <Pen Thickness="0.7" Brush="Black"/>
                </GeometryDrawing.Pen>
            </GeometryDrawing>
        </DrawingBrush.Drawing>
    </DrawingBrush>
    

    Then write a DataTrigger like this:

    <DataTrigger Binding="{Binding IsHatchBrush}" Value="True">
        <Setter Property="OpacityMask" Value="{StaticResource HatchBrush}" />
    </DataTrigger>