Search code examples
wpfxamlresourcespathgeometry

How to use PathFigure from resources in PathGeometry?


I wonder whether is there any way to use a PathFigure from resources in PathGeometry element in xaml. Let's say I have a ResourceDictionary and a two PathFigure objects inside it with the 'x:Key' attributes equal to "Figure1" and "Figure2" respectively. My goal is to create a PathGeometry with Figures property filled with a collection containing Figure1 and Figure2. I can do it so easily with a code behind file, however I would like to know is there any way to do it with xaml only.

<PathFigure IsClosed="True" StartPoint="2,9" x:Key="Figure1">
    <ArcSegment Point="15,9" Size="6.5, 2"/>
    <LineSegment Point="15,12"/>
    <ArcSegment Point="2,12" Size="6.5, 2"/>
</PathFigure>

<PathFigure IsClosed="True" StartPoint="10,7" x:Key="Figure2">
    <LineSegment Point="10, 2"/>
    <LineSegment Point="13,2"/>
    <LineSegment Point="13,7"/>
    <ArcSegment Point="10,7" Size="2,2" IsLargeArc="True"/>
</PathFigure>

I can create now a PathGeometry :

<PathGeometry FillRule="Nonzero" x:Key="1">
    <PathFigureCollection>
        //Here I want to put Figure1 and Figure2
    </PathFigureCollection>
</PathGeometry>

I think I can write some kind of MarkupExtension to do the following, but I am looking for the best way. Thanks for your advices.


Solution

  • You don't need anything special just the already built-in StaticResourceExtension class (markup extension).

    <Window.Resources>
        <PathFigure IsClosed="True" StartPoint="2,9" x:Key="Figure1">
            <ArcSegment Point="15,9" Size="6.5, 2"/>
            <LineSegment Point="15,12"/>
            <ArcSegment Point="2,12" Size="6.5, 2"/>
        </PathFigure>
    
        <PathFigure IsClosed="True" StartPoint="10,7" x:Key="Figure2">
            <LineSegment Point="10, 2"/>
            <LineSegment Point="13,2"/>
            <LineSegment Point="13,7"/>
            <ArcSegment Point="10,7" Size="2,2" IsLargeArc="True"/>
        </PathFigure>
    
        <PathGeometry FillRule="Nonzero" x:Key="OneAndTwo">
            <StaticResource ResourceKey="Figure1" />
            <StaticResource ResourceKey="Figure2" />
        </PathGeometry>
    </Window.Resources>
    

    Usage:

    <Path Stroke="Black" StrokeThickness="1" Data="{StaticResource OneAndTwo}" />