Question

I would like to load vector graphics stored as XAML files (separate files, not in a dictionary), embedded in my application, and I have a few questions to do so:

  1. XAML looks a bit ambiguous, since it can be used to represent either static resources like vector images, or interfaces which are being dynamically built like the ones in WPF. Because of this, the format of a XAML vector image is unclear to me : what should be the root element, like the "svg" tag for svg vector images ? Currently, I'm using a Canvas as the top element since I want to plot my graphics in another Canvas.

  2. What is the best method to load those file programmatically (I mean, to create the Canvas from the xaml files) ? I've seen (and tried) different solutions with XamlReader, but nothing worked: the app crashes and the debugger does not help (most problems I've encountered seem to occur during the parsing, and the error message was unclear).

I've read http://learnwpf.com/post/2006/06/04/How-do-I-Include-Vector-Based-Image-Resources-in-my-WPF-Application.aspx, but the link to the article dealing with resource files loading is dead, and the images are not created using C# code.

Was it helpful?

Solution

Okay, I found the solution by myself and here it is :

My project is named "Editor", and I've placed the XAML file I want to read in a "Graphics" folder. This file is named "Image.xaml". The project tree looks like this :

enter image description here

The XAML file itself holds this code :

<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Width="40" Height="40">
    <Rectangle Canvas.Left="0" Canvas.Top="0" Fill="White" Stroke="Black" StrokeThickness="1" Height="40" Width="40" />
    <!-- ... -->
</Canvas>

(the xaml namespace 'xmlns' reference is needed)

The code used to load the file is :

StreamResourceInfo sr = Application.GetResourceStream(new Uri("Editor;component/Graphics/Image.xaml", UriKind.Relative));
Canvas result = (Canvas)XamlReader.Load(new XmlTextReader(sr.Stream));
layoutRoot.Children.Add(result);

'layoutRoot' being the name of the main Canvas of my application.

Last subtility : the property 'BuildAction' of the *.xaml file must be set to 'Resource', or you will encounter a XamlParseException with hexadecimal value 0x0C (to change this property, right-click on the file in the project treeview).

Hope this can help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top