views:

1687

answers:

1

I have a few internal Canvas xaml files which I want to load dynamically at runtime. For example, I want to display the Canvas in a page. However, I cannot seem to get it to work. I've tried using XamlReader, Application.LoadComponent, and using an XDocument; all to no avail. I cannot seem to find the best practice for this on-line either.

The Canvases are stored like this: MyApp/Resources/Logos/Logo1.xaml. I'm not sure if Logo1.xaml should have a build action of "Component" or "Resource". In any case, using the URI of "MyApp;components/Resources/Logos/Logo1.xaml" seems to be correct, but Application.LoadComponent gets an XamlParseException at Line 0 Position 0.

Here's a pseudo-example of Logo1.xaml:

<Canvas
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="286.233" Height="143.425">

    <Canvas>

        <Path />

        <Path />

        <Path />

        <Path />

    </Canvas>
</Canvas>

The data for the path elements has been omitted for brevity's sake.

Any ideas?

+1  A: 

I got this to work using build action "Resource" and the XamlLoader with a ContentControl:

var resourceName = string.Format("MyApp;component/Resources/Logos/{0}.xaml", logoName);
var uri = new Uri(resourceName, UriKind.Relative);
var streamResourceInfo = Application.GetResourceStream(uri);

string xaml = null;

using (var resourceStream = streamResourceInfo.Stream)
{
    using (var streamReader = new StreamReader(resourceStream))
    {
        xaml = streamReader.ReadToEnd();
    }
}

Canvas canvas = XamlReader.Load(xaml) as Canvas;

this.contentControl.Content = canvas;
Edward Stembler