Alex Rivera | Logout

Creating a Silverlight DataTemplate in code

Asked 2008-09-12T16:31:06.130
28

How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.

Edit: Here's the code I'm now using this for, based on the answer from Santiago below.

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

This works really nicely and allows me to change the binding on the fly.

Edit
Report

1 Answer

11

I had a few problems with this code, getting element not foung exceptions. Just for reference, it was that I needed my namesspace included in the DataTemplate...

private DataTemplate Create(Type type)
        {
            string xaml = @"<DataTemplate 
                xmlns=""http://schemas.microsoft.com/client/2007""
                xmlns:controls=""clr-namespace:" + type.Namespace + @";assembly=" + type.Namespace + @""">
                <controls:" + type.Name + @"/></DataTemplate>";
            return (DataTemplate)XamlReader.Load(xaml);
        }
answered 2008-12-10T13:38:31.160

Your Answer