我想将相同的属性应用于我的所有多边形:
Polygon polygon = new Polygon();
polygon.StrokeThickness = 2;
polygon.Stroke = Brushes.Black;
polygon.Fill = (Brush)FindResource("HatchBrush");
polygon.ToolTip = (Image)FindResource("GapImg");
我该怎么做?
答案 0 :(得分:2)
您可以使用Style
property。
在资源字典中定义样式:
<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
,您甚至无需找到资源运行时。
答案 1 :(得分:1)
将您在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,那么您需要用DynamicResource替换StaticResource行