locked
Is it possible to define a TemplateContent in procedural code?

    Question

  • I need to set a Template ( type: TemplateContent ) property of a HierarchicalDataTemplate instance.  Like this:

     

    HierarchicalDataTemplate hdt = new HierarchicalDataTemplate();

    hdt.Template = (TemplateContent)someUserControl;

     

    But it doesn't work because template and instance are different things.

     

    Is there a way?

     

    Tuesday, December 07, 2010 11:56 PM

Answers

  • Well, if you wanted to do everything in code, you could do something like:

    HierarchicalDataTemplate hdt = new HierarchicalDataTemplate();
    
    StringReader stringReader = new StringReader(CreateItemTemplate());
    XmlReader xmlReader = XmlReader.Create(stringReader);
    
    hdt.ItemTemplate = (DataTemplate)XamlReader.Load(xmlReader);
    

    The CreateItemTemplate method would look something like:

    private string CreateItemTemplate() 
    {
      StringBuilder template = new StringBuilder();
      template.Append("<DataTemplate "); 
      template.Append("xmlns='http://schemas.microsoft.com/winfx/"); 
      template.Append("2006/xaml/presentation' ");
      template.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>");
      template.Append("<TextBlock Text='{Binding}'/>"); 
      template.Append("</DataTemplate>"); 
      return template.ToString(); 
    }
    
    
    • Marked as answer by Cartaxo Wednesday, December 22, 2010 8:09 PM
    Wednesday, December 22, 2010 7:38 PM