2

我想将相同的属性应用于我的所有多边形:

Polygon polygon = new Polygon();
polygon.StrokeThickness = 2;
polygon.Stroke = Brushes.Black;
polygon.Fill = (Brush)FindResource("HatchBrush");
polygon.ToolTip = (Image)FindResource("GapImg");

我怎样才能做到这一点?

4

2 回答 2

2

您可以使用该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>

然后对每个使用FindResourcePolygon

Polygon polygon = new Polygon() 
{ 
    Style = FindResource("PolygonStyle") as Style,
};

如果您需要将样式应用于所有多边形,只需删除x:Key,您甚至不需要找到资源run-time

于 2012-06-15T12:53:53.740 回答
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 是在运行时创建的,那么您需要将 StaticResource 行替换为 DynamicResource

于 2012-06-15T13:04:47.287 回答