title: Creating a DataTemplate in Code: Can I use the Template property?
body: <p>I'm attempting to use a <code>DataTemplateSelector</code> with a particular third-party WPF grid control, and I'm having trouble determining if the issues I'm having are a bug in the control or my own lack of understanding about the conventions of WPF data templates.</p>
  
  <p>I realize that the ordinary use case of a <code>DataTemplate</code> is to declare it somewhere in XAML (be it as a resource or explicitly where it's used), but my particular project would benefit greatly if I could create the template in code (C#, specifically) rather than in XAML. The issue I'm running into is the fact that my code-created <code>DataTemplate</code> uses a <code>FrameworkElementFactory</code> as the template's <code>VisualTree</code>, whereas a XAML-created template uses a <code>TemplateContent</code> object as the template's <code>Template</code> value. As best I can tell right now, the grid control in question works with templates that use <code>Template</code>, but doesn't seem to play nicely with templates that use <code>VisualTree</code>.</p>
  
  <p>By way of comparison, here's what one of the templates looks like in XAML as part of my selector:</p>
  
  <pre><code>&lt;MySelectorType&gt;
      &lt;MySelectorType.BooleanTemplate&gt;
          &lt;DataTemplate&gt;
              &lt;EditorControl Name="Reserved_Name" /&gt;
          &lt;/DataTemplate&gt;
      &lt;/MySelectorType.BooleanTemplate&gt;
  &lt;/MySelectorType&gt;
  </code></pre>
  
  <p>And here's how I'm trying to create an equivalent template in code:</p>
  
  <pre><code>var template = new DataTemplate()
  {
      VisualTree = new FrameworkElementFactory(typeof(EditorControl)) 
                   { 
                       Name = "Reserved_Name" 
                   }
  };
  </code></pre>
  
  <p>I've also tried it like this:</p>
  
  <pre><code>var template = new DataTemplate()
  {
      VisualTree = new FrameworkElementFactory(typeof(EditorControl))
  };
  
  template.VisualTree.SetValue(EditorControl.NameProperty, "Reserved_Name");
  </code></pre>
  
  <p>Which seemed more analogous to what the XAML template would do, but that appeared not to work <em>at all</em> (the editor neither read or set the value, where at least the first version would read it).</p>
  
  <p>Is it possible for my in-code template to use the <code>Template</code> property rather than <code>VisualTree</code>? According to <a href="http://msdn.microsoft.com/en-us/library/system.windows.templatecontent.aspx" rel="nofollow">the documentation</a>, there's no public API for this type and the instantiation path is complex, but has this been done? The only <a href="http://social.msdn.microsoft.com/Forums/en/vswpfdesigner/thread/d897806e-36ce-464e-9bbe-4640a2a5a006" rel="nofollow">example</a> I've found uses hardcoded XAML in the code, which doesn't sit well with me.</p>