C# – Using a XAML file as a vector Image Source

cvector-graphicswpfxaml

I would like to be able to use vector graphics, preferably defined in XAML, as the Source of an Image control, just like I can currently use a raster image like a PNG. That way I could easily mix and match between bitmap and vector images, like this:

<StackPanel>
    <Image Source="Images/Namespace.png"/>
    <Image Source="Images/Module.xaml"/>
</StackPanel>

Module.xaml would most likely have <DrawingImage> as its root element instead of <UserControl>.

Actually, what I'm really going for is this, so my ViewModel could select either a raster or vector image at its discretion:

<Image Source="{Binding ImageUri}"/>

Is this possible? Can Image.Source load XAML classes from a given URI? Or is it only able to load bitmap resources?

Best Answer

You can simply reference your vector graphics as StaticResources:

<Image Source="{StaticResource MyImage}" />

Store the images in a ResourceDictionary as DrawImage's. Expression Blend can help you generate this stuff:

<ResourceDictionary
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

   <DrawingImage x:Key="MyImage">
      <DrawingImage.Drawing>
         <DrawingGroup>
            <DrawingGroup.Children>
               <GeometryDrawing Brush="Black" Geometry="M 333.393,... 100.327 Z "/>
               <GeometryDrawing Brush="Black" Geometry="F1 M 202.309,... Z "/>
                      :
            </DrawingGroup.Children>
         </DrawingGroup>
     </DrawingImage.Drawing>
   </DrawingImage>

</ResourceDictionary>
Related Topic