将相同的属性应用于我的所有多边形
本文关键字:我的 多边形 应用于 属性 | 更新日期: 2023-09-27 18:37:24
我想将相同的属性应用于我的所有多边形:
Polygon polygon = new Polygon();
polygon.StrokeThickness = 2;
polygon.Stroke = Brushes.Black;
polygon.Fill = (Brush)FindResource("HatchBrush");
polygon.ToolTip = (Image)FindResource("GapImg");
我该怎么做?
您可以使用
Style
属性。
在资源字典中定义样式:
<Style x:Key="PolygonStyle" TargetType="Polygon">
<Setter Property="Stroke" Value="Black" />
<Setter Property="StrokeThickness" Value="2" />
<Setter Property="Fill" Value="{StaticResource HatchBrush}" />
<Setter Property="ToolTip" Value="{StaticResource GapImg}" />
</Style>
然后为每个Polygon
使用 FindResource:
Polygon polygon = new Polygon()
{
Style = FindResource("PolygonStyle") as Style,
};
如果您需要将样式应用于所有多边形,只需删除x:Key
,您甚至不需要找到资源运行时。
将你在 XAML 中提供的样式放在 App.xaml 文件中。
<Application x:Class="WpfApplication10.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!-- Demo resources -->
<SolidColorBrush x:Key="HatchBrush" Color="Red"/>
<Image x:Key="GapImg" Source=".."/>
<Style x:Key="PolygonStyle" TargetType="Polygon">
<Setter Property="Stroke" Value="Black" />
<Setter Property="StrokeThickness" Value="2" />
<Setter Property="Fill" Value="{StaticResource HatchBrush}" />
<Setter Property="ToolTip" Value="{StaticResource GapImg}"/>
</Style>
</Application.Resources>
</Application>
如果资源 HatchBrush 和 GapImg 是在运行时创建的,则需要将 StaticResource 行替换为 DynamicResource