title: How to set x:Name with FrameworkElementFactory in WPF?
body: <p>I am creating a Datatemplate in code that is retrieved by a Datatemplate selector. I can not create the datatemplate in xaml due to some business rules. I am using Devexpress' PropertyGridControl with customs Property Definitions.</p>
  
  <p>The datatemplate is overriding the PropertyDefinition's CellTemplate, therefore the control inside the template must have <strong>x:Name = "PART_Editor"</strong>. The control inside the datatemplate is a TrackBarEdit, but it could be any editor control.</p>
  
  <p>Here is the code for my template builder:</p>
  
  <pre><code>private DataTemplate BuildTemplate()
      {
          var trackbarFactory = new FrameworkElementFactory(typeof(MyTrackBar));
          trackbarFactory.SetValue(RangeBaseEdit.MaximumProperty, 5.0);
          trackbarFactory.SetValue(MyTrackBar.NameProperty,"PART_Editor");
          var trackbarTemplate = new DataTemplate
          {
              VisualTree = trackbarFactory
          };
          trackbarTemplate.Seal();
  
          var propDefinitionFactory = new FrameworkElementFactory(typeof(PropertyDefinition));
          propDefinitionFactory.SetBinding(PropertyDefinitionBase.PathProperty,new Binding(nameof(PropertyStore.Name)));
          propDefinitionFactory.SetBinding(PropertyDefinitionBase.IsReadOnlyProperty,new Binding("Metadata.ForceReadOnly"));
          propDefinitionFactory.SetValue(PropertyDefinition.CellTemplateProperty,trackbarTemplate);
          var propDefinitionTemplate = new DataTemplate
          {
              VisualTree = propDefinitionFactory
          };
          propDefinitionTemplate.Seal();
  
          return propDefinitionTemplate;
      }
  </code></pre>
  
  <p>The control renders properly with all the bindings, but I can not figure out how to set <strong>x:Name</strong> through the frameworkElementFactory. I have tried to set <strong>FrameworkElement.NameProperty</strong> and even to inherit TrackbarEdit to create a new DependencyProperty mapped to x:Name via <strong>RuntimeNamePropertyAttribute</strong> but it does not work.</p>
  
  <p>As a consequence the editor rendered does not update the bound property's value.</p>