Reusable polygon
I want to have a canvas in xaml where i place some icons. These icons are polygons like this one:
<Polygon Points="0,0 20,50, 0,50 20,0" Fill="Red" Stretch="Uniform"/>
But i want to use an icon several times, so i want to define it in the resources and include it by reference into the canvas at a certain position, someway like this:
<Page.Resources>
<Polygon Key="icon1" Points="0,0 20,50, 0,50 20,0" Fill="Red" Stretch="Uniform"/>
<Polygon Key="icon2" Points="0,0 10,30, 10,60 20,0" Fill="Blue" Stretch="Uniform"/>
...
</Page.Resources>
<Canvas>
<Polygon Reference="icon1" X="0" Y="0"/>
<Polygon Reference="icon2" X="10" Y="10"/>
<Polygon Refer开发者_StackOverflow社区ence="icon1" X="20" Y="20"/>
...
</Canvas>
I found a possible solution on http://www.codeproject.com/KB/WPF/GraphicInXAMLAndWPF.aspx where the polygons are stored in a drawing image, but seems to be to much overhead.
Someone has an better idea how to solve this?
Probably the most obvious and flexible method is to create a UserControl. You can add a new file of type UserControl from the solution explorer, add your Polygon to the 'LayoutRoot' Grid that Visual Studio will create. You can then create as many instances as you like of your user control!
However, checking for similar problems on SO, you could use a content control to render the polygon, note, you would have to use x:Shared="false" to ensure that you are not trying to re-use the same polygon each time.
<Page.Resources>
<Polygon x:Key="icon1" x:Shared="False"
Points="0,0 20,50, 0,50 20,0" Fill="Red" Stretch="Uniform"/>
<Polygon x:Key="icon2" x:Shared="False"
Points="0,0 10,30, 10,60 20,0" Fill="Blue" Stretch="Uniform"/>
...
</Page.Resources>
<Canvas>
<ContentControl Content="{StaticResource icon1}" Canvas.Top="0" Canvas.Left="0"/>
<ContentControl Content="{StaticResource icon2}" Canvas.Top="0" Canvas.Left="10"/>
<ContentControl Content="{StaticResource icon1}" Canvas.Top="0" Canvas.Left="20"/>
...
</Canvas>
See the following:
Vector image as reusable XAML fragment
精彩评论