c# - 如何以编程方式修改 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));
问题在于它将路径描边颜色设置为红色而不是蓝色,并且不会更改网格背景颜色。
解决方案
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);
推荐阅读
- python-3.x - 如何使用 Tkinter 在屏幕上显示游戏?
- android - 使用轮播管理器库时回收站视图未更新
- ios - View Controller not conforming to protocol, even though all methods are implemented
- postgresql - 循环请求。提出超过 15 小时的请求
- r - 尝试将多个列与 mapply 组合创建巨大的列表
- python - 如何根据随机打印的内容制作 if 语句?
- wagtail - 如何在 wagtail 管理员中过滤页面列表,以便编辑者只能看到他们创建的页面?
- python - 在类中调用嵌套函数
- fabricjs - 更改了椭圆对象,但在 fabric.js 中没有发出事件
- android - 如何在 Flutter 中渲染单个像素?