C# 如何以编程方式修改VisualBrush?

C# 如何以编程方式修改VisualBrush?,c#,wpf,visualbrush,C#,Wpf,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

在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>

问题是它将路径笔划颜色设置为红色而不是蓝色,并且不更改网格背景颜色。

我发现了问题

首先。Xaml中的栅格高度为0,因此背景不可见。但我认为,由于抗锯齿,部分颜色在路径中可见。向网格添加高度可以解决背景色的问题

<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>

您是否考虑过不以编程方式更改资源的颜色,而是创建一个包含新背景颜色和路径笔划的第二样式资源,然后以编程方式重新分配控件的样式?@Mac感谢您的回答。不幸的是,我有很多用Xaml创建的可视化画笔,我只需要通过编程更改颜色。在本例中,我更改为蓝色和红色,但它可以是用户首选的任何颜色和组合。如果您希望能够修改对象,为什么要使用
PresentationOptions:Freeze
?坦率地说,与使用视图模型和绑定来控制这样的事情相比,直接在代码隐藏中设置属性是非常糟糕的设计选择。但至少,如果你想修改一个对象,你可能不应该告诉WPF你不想修改该对象。@PeterDuniho我需要PresentationOptions:Freeze,因为性能原因,但这不是问题所在,因为我从资源中创建了一个新的VisualBrush,它是可修改的,然后我再次冻结它,然后将其分配给控件背景。我需要以编程的方式来做,因为我必须从设置文件“我从资源中创建了一个新的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" Height = 40>
            <Path Data="M 0 0 L 40 0" Stroke="White" />
        </Grid>
    </VisualBrush.Visual>
</VisualBrush>
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);