首页 > 解决方案 > 如何以编程方式修改 VisualBrush?

问题描述

在 xaml Window.Resources 我定义了一个 VisualBrush:

    <VisualBrush x:Name="LineVisualBrush" x:Key="LineVisualBrush" TileMode="Tile" Viewport="0,0,40,40" ViewportUnits="Absolute" Viewbox="0,0,40,40" ViewboxUnits="Absolute" PresentationOptions:Freeze="True">
        <VisualBrush.Visual>
            <Grid Background="Black">
                <Path Data="M 0 0 L 40 0" Stroke="White" />
            </Grid>
        </VisualBrush.Visual>
    </VisualBrush>

在后面的代码中,我需要更改网格背景颜色和路径描边颜色:

        VisualBrush vb = new VisualBrush();
        vb = (VisualBrush)Resources["LineVisualBrush"];

        vb.Visual.SetValue(Grid.BackgroundProperty, new SolidColorBrush(Colors.Red));
        vb.Visual.SetValue(Shape.StrokeProperty, new SolidColorBrush(Colors.Blue));

问题在于它将路径描边颜色设置为红色而不是蓝色,并且不会更改网格背景颜色。

标签: c#wpfvisualbrush

解决方案


I have found the problems.

First. The Grid in Xaml have Height 0 for this reason the background is not visible. But I think because of Antialias a part of the color is visible in the Path. Adding an Height to the Grid it fix the problem about Background color.

<VisualBrush x:Name="LineVisualBrush" x:Key="LineVisualBrush" TileMode="Tile" Viewport="0,0,40,40" ViewportUnits="Absolute" Viewbox="0,0,40,40" ViewboxUnits="Absolute" PresentationOptions:Freeze="True">
    <VisualBrush.Visual>
            <Grid Background="Black" Height = 40>
            <Path Data="M 0 0 L 40 0" Stroke="White" />
        </Grid>
    </VisualBrush.Visual>
</VisualBrush>

Second. I need to access the children of the Visual in code behind to change te Stroke color of the Path. I changed the code in this way and now it works perfectly.

VisualBrush vb = (VisualBrush)Resources["LineVisualBrush"];
Grid grid = (Grid)vb.Visual;
System.Windows.Shapes.Path path = (System.Windows.Shapes.Path)grid.Children[0];
grid.Background = new SolidColorBrush(Colors.Red);
path.Stroke = new SolidColorBrush(Colors.Blue);

推荐阅读