views:

1021

answers:

2

Seem to be having a lot of problems doing what should be simple things with XAML / WPF - I have created some XAML-based images using shapes like Rectangle and Ellipse to create icons which I need other parts of my application to use - but I cannot seem to find out how to do this - I seem to be able to store a Canvas in the Resource Dictionary but no way of using it in any other Window. How is this done - these are simple images just two or three shapes I want to use throughout my project!
The images must also be resizable - I know how to store paths, however these shapes contain gradient styles I want preserved plus I don't know how the rectangle could convert to path and colour data.

Thanks!

+3  A: 

You don't want to be using a Canvas to store these resources in a Resource Dictionary. The root of your geometry is probably something like a DrawingBrush (especially if you used Expression Design to create the images), and those are the items that would need to be added to a Resource Dictionary like so:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
    <DrawingBrush x:Key="YourResourceKey">
<DrawingBrush.Drawing>
<DrawingGroup>
<!-- This can change a lot, but a typical XAML file exported from a Design image would have the geometry of the image here as a bunch of Paths or GeometryDrawings -->
</DrawingGroup>
</DrawingBrush.Drawing>
</ResourceDictionary>

I'll assume you know how to get this Resource Dictionary referenced in your application.

To use the Resources, you simply would assign them to the appropriate properties. For shape-type images, you can assign them to something like the Fill property of a Rectangle (there are plenty of other ways, but this is a simple one). Here's one example:

<Button>
   <Grid>
      <Rectangle Fill="{StaticResource YourResourceKey}" />
   </Grid>
</Button>
KP Adrian
+3  A: 

You should use a Drawing and display it using a DrawingBrush like KP Adrian suggested or a DrawingImage and an Image control, but if you can't use a drawing you can use a Canvas inside a VisualBrush.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
<Page.Resources>
    <VisualBrush x:Key="Icon">
        <VisualBrush.Visual>
            <Canvas Width="10" Height="10">
                <Ellipse Width="5" Height="5" Fill="Red"/>
                <Ellipse Width="5" Height="5" Fill="Blue" Canvas.Left="5" Canvas.Top="5"/>
            </Canvas>
        </VisualBrush.Visual>
    </VisualBrush>
</Page.Resources>
    <Rectangle Width="100" Height="100" Fill="{StaticResource Icon}"/>
</Page>
Nir