title: WPF, UserControl or DataTemplate
body: <p>Recently I'm trying to reuse some UI elements in my application. When I started programming with WPF I'm told that DataTemplate is the best way to reuse UI elements. You can define a template for your data entity and use it everywhere. It sounds very good. 
  However, I also found some disadvantages, especially when it is compared with UserControl. </p>
  
  <ol>
  <li>You cannot reuse a DataTemplate defined in another Window or UserControl. For example, if UserDataTemplate is define in WindowA.xaml, you cannot use it in WindowB.xaml. The solution might be that put the DataTemplate as a resource in a global Resource Dictionary.</li>
  <li>DataTemplate is hard to have some code behind. As mentioned in item 1, if you put the DataTemplate in a ResourceDictionary, there is no place to put your code by default. I googled the problem and yes, I found a trick to make the  ResourceDictionary have a cs file. But it still has another problem.</li>
  <li><p>Another problem of DataTemplate is that you must be clear with the difference between the instance of DataTemplate itself and the instances of the content of DataTemplate. A DataTemplate will have only one "instance of DataTemplate", and may have many instances of the content of the DataTemplate. Let me explain it with an Example:</p>
  
  <pre><code>&lt;DataTemplate&gt;
          &lt;DataTemplate.Resources&gt;
                  &lt;my:User x:key="User1"/&gt;
          &lt;/DataTemplate.Resources&gt;                
          &lt;Grid MouseLeftButtonDown="OnMouseLeftButtonDown"&gt;
                  &lt;Grid.Resources&gt;
                          &lt;my:User x:key="User2"/&gt;
                  &lt;/Grid.Resources&gt;
          &lt;/Grid&gt;        
  &lt;/DataTemplate&gt;
  
  
  public partial class CodeBehind
  {
           Point mousePos = new Point();
  
          private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
          {
                  mousePos = e.Pos...;
          }
  }
  </code></pre></li>
  </ol>
  
  <p>The result will be that : User1 will only have one instance, however, a User2 instance will be created once the DataTemplate is applied, which means User2 will have many instances if the datatemplate is being applied many times.
  However, unlike UserControl, the field "mousePos" will NOT have many copies. If the DataTemplate is being applied 100 times, the mousePos won't have 100 copies, which mean the 100 Grids will use the only one mousePos field as the same time, which may cause problems.
  In UserControl, the field you defined will only be used by the control. 100 UserControl instances will have 100 field copies.</p>
  
  <p>Maybe I'm using DataTemplate in the wrong way. Any comment is appreciated.</p>
  
  <p>Best regards,</p>
  
  <p>Zach</p>