Friday, June 03, 2011

Silverlight Tip of the Day #60 – How to load a XAML Control From a File or String

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));