Friday, February 1, 2013

How to dynamically load internal xaml in Silverlight?

Logo.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>
 
 
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; 

No comments: