title: How can I use an ElementName binding within a ControlTemplate?
body: <p>I have multiple TextBlocks which reference different elements in my application.  My code works fine when used directly in the page.  However, I want to create a ControlTemplate and a ContentControl to reduce the duplication of code.  </p>
  
  <p>How can I pass a reference to an ElementName into the ControlTemplate from the ContentControl using TemplateBinding?  The following code throws this error: </p>
  
  <blockquote>
    <p>"Cannot convert the value in attribute 'ElementName' to object of type
    'System.String'. Object of type
    'System.Windows.TemplateBindingExpression' cannot be converted to type
    'System.String'.  "</p>
  </blockquote>
  
  <p>In addition to the Tag attribute, I have tried ContentStringFormat which also did not work.  </p>
  
  <p>What is the correct method to get this to work using templates?</p>
  
  <p>Thanks in advance for your help,</p>
  
  <p>--- Shawn</p>
  
  <p>Here is the code sample:</p>
  
  <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" &gt;
      &lt;Page.Resources&gt;
          &lt;ControlTemplate x:Key="MyTemplate" TargetType="{x:Type ContentControl}"&gt;
              &lt;TextBlock Margin="{Binding ElementName={TemplateBinding Tag}, Path=Margin}" Text="{TemplateBinding Content}" TextAlignment="{Binding ElementName={TemplateBinding Tag}, Path=TextAlignment}" Width="{Binding ElementName={TemplateBinding Tag}, Path=Width}" /&gt;
          &lt;/ControlTemplate&gt;
      &lt;/Page.Resources&gt;
      &lt;StackPanel&gt;
          &lt;TextBlock x:Name="AnotherElement" Margin="10" Text="Main TextBlock" TextAlignment="Center" Width="100" /&gt;
          &lt;TextBlock x:Name="AnotherElement2" Margin="20" Text="Second TextBlock" TextAlignment="Left" Width="250" /&gt;
          &lt;TextBlock Margin="{Binding ElementName=AnotherElement, Path=Margin}" Text="Here is my TextBlock!" TextAlignment="{Binding ElementName=AnotherElement, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement, Path=Width}" /&gt;
          &lt;TextBlock Margin="{Binding ElementName=AnotherElement2, Path=Margin}" Text="Here is my Second TextBlock!" TextAlignment="{Binding ElementName=AnotherElement2, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement2, Path=Width}" /&gt;
          &lt;ContentControl Content="Hello!" Tag="AnotherElement" Template="{StaticResource MyTemplate}" /&gt;
          &lt;ContentControl Content="Hello Again!" Tag="AnotherElement2" Template="{StaticResource MyTemplate}" /&gt;
      &lt;/StackPanel&gt;
  &lt;/Page&gt;
  </code></pre>