tags:

views:

7519

answers:

6

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""&gt;
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
            </DataTemplate>"
   );
}

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

+1  A: 

citation from MSDN: "The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element. "

jarda
+15  A: 

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""&gt;
                <" + 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.

Great answer - no idea why I didn't think of it myself!
Nick R
+8  A: 

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)
        {
            DataTemplate dt = new DataTemplate();
            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);
        }
You don't need the statement "DataTemplate dt = new DataTemplate();" because it is not used.
Phillip Ngan
**Assembly name != Namespace name** though.
herzmeister der welten
A: 

Thank ou so much for your help...

A: 

Thank you so much . It really helped me :)

Naseem
A: 

Is there any way to do this in code (without using a string)?

I have a data template which includes, Bindings, Converters and ConverterParameters, it's very difficult to construct it as a string object, and impossible to debug.

Michael