Creating a Silverlight DataTemplate in code

Although you cannot programatically create it, you can load it from a XAML string in code like this:

    public static DataTemplate Create(Type type)
    {
        return (DataTemplate) XamlReader.Load(
            @"<DataTemplate
                xmlns=""http://schemas.microsoft.com/client/2007"">
                <" + type.Name + @"/>
              </DataTemplate>"
          );
    }

The snippet above creates a data template containing a single control, which may be a user control with the contents you need.

Leave a Comment