wpfvisualbrush

VisualBrush with fading margins in WPF


I'm trying to create a VisualBrush with a hatched pattern that would fade at the top and bottom margins. While I had no problem with hatch itself:

<VisualBrush x:Key="b1" TileMode="Tile" Viewport="0,0,15,15" ViewportUnits="Absolute" Viewbox="0,0,15,15" ViewboxUnits="Absolute">
    <VisualBrush.Visual>
        <Canvas>
            <Path Data="M 0 15 L 15 0" Stroke="Gray"></Path>
            <Path Data="M 0 0 L 15 15" Stroke="Gray"></Path>
        </Canvas>
    </VisualBrush.Visual>    
</VisualBrush>

I don't really see a way to make it fade. Any idea how to do this?

Trying to get a background as per image below.

enter image description here


Solution

  • As I understood from your example image, you need to specify a general Background. For this I setting Grid instead Canvas and set for him Background color.

    For panel which will display the content need to set OpasityMask like this:

    <Window.Resources>
        <VisualBrush x:Key="b1" TileMode="Tile" Viewport="0,0,15,15" ViewportUnits="Absolute" Viewbox="0,0,15,15" ViewboxUnits="Absolute">
            <VisualBrush.Visual>
                <Grid Background="Black">
                    <Path Data="M 0 15 L 15 0" Stroke="Gray" />
                    <Path Data="M 0 0 L 15 15" Stroke="Gray" />
                </Grid>
            </VisualBrush.Visual>
        </VisualBrush>
    </Window.Resources>
    
    <Grid Background="{StaticResource b1}">
        <Grid.OpacityMask>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                <GradientStop Offset="0" Color="Black" />
                <GradientStop Offset="1" Color="Transparent" />
            </LinearGradientBrush>
        </Grid.OpacityMask>
    
        <Label Content="TEST" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
    

    Result

    enter image description here