C# 将相同的属性应用于我的所有多边形
我想对所有多边形应用相同的属性:C# 将相同的属性应用于我的所有多边形,c#,wpf,C#,Wpf,我想对所有多边形应用相同的属性: Polygon polygon = new Polygon(); polygon.StrokeThickness = 2; polygon.Stroke = Brushes.Black; polygon.Fill = (Brush)FindResource("HatchBrush"); polygon.ToolTip = (Image)FindResource("GapImg"); 我怎样才能做到这一点?您可以使用 在资源字典中定义样式: <Style
Polygon polygon = new Polygon();
polygon.StrokeThickness = 2;
polygon.Stroke = Brushes.Black;
polygon.Fill = (Brush)FindResource("HatchBrush");
polygon.ToolTip = (Image)FindResource("GapImg");
我怎样才能做到这一点?您可以使用
在资源字典中定义样式:
<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>
如果您需要将样式应用于所有多边形,只需删除
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线替换为DynamicSource您只需省略x:键并将其应用于所有多边形,而无需找到资源并设置其样式。感谢Andy+1,为什么是Application.Resources?它实际上不需要进入app Resources,它可以进入您正在绘制的多边形范围内的任何资源字典,因此如果您只想设置多边形的单个窗口的样式,可以将其添加到window.Resources集合中
<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>