first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

Silverlight: “Silverlight Tip of the Day #60—How to load a XAML Control From a File or String”; Mike Snow

If you have a control written in XAML that is included in your project you can load and create it directly from file by using the method:

System.Windows.Markup.XamlReader.Load().This method can also be used to directly create a Silverlight control from a string.

To demonstrate this I have created two functions called LoadFromXAML(). The first function takes takes as a parameter a URI that points to the XAML file in your project you want to load. The second takes as a parameter a string representation of the control.

public static object LoadFromXaml(Uri uri) { System.Windows.Resources.StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(uri);

if ((streamInfo != null) && (streamInfo.Stream != null))
{
    using (System.IO.StreamReader reader = new System.IO.StreamReader(streamInfo.Stream))
    {
        return System.Windows.Markup.XamlReader.Load(reader.ReadToEnd());
    }

}
return null;

}

public static object LoadFromXamlString(string xamlControl) { return System.Windows.Markup.XamlReader.Load(xamlControl); }

The above methods return a generic object that can be typecast to the object you are loading. For example:

Button myButton = (Button)LoadFromXaml(new Uri("/LoadXaml;component/MyButton.xaml", UriKind.Relative));

or

string buttonXAML = "<Button x­mlns='http://schemas.microsoft.com/client/2007' Width=\\"100\\" Height=\\"100\\" Content=\\"Click Me\\"></Button>";

Button myButton = (Button) LoadFromXaml(buttonXAML);

Note that in the XAML you must declare a default XML namespace as highlighted below:

<Button x­mlns='http://schemas.microsoft.com/client/2007' Width="100" Height="100" Content="Click Me"></Button>

If you do not declare this namespace, you will see the following error:

AG_E_PARSER_MISSING_DEFAULT_NAMESPACE [Line: 0 Position: 0]

[http://silverlight.net/blogs/msnow/archive/2008/10/09/ silverlight-tip-of-the-day-60-how-to-load-a-control-straight-from-xaml.aspx]

mod date: 2009-08-10T04:19:00.000Z