Binding ElementName. Does it use Visual Tree or Logical Tree

I think it’s logical tree. When using ControlTemplates, you’re replacing one visual tree with another, but I don’t think you can reference the names defined inside of the ControlTemplate.

For example:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.Resources>
            <ControlTemplate x:Key="Foo" TargetType="Button">
                <Border x:Name="border" Background="Red">
                    <Label Content="{TemplateBinding Content}"></Label>
                </Border>
            </ControlTemplate>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Button x:Name="buttonFoo" Background="Green" HorizontalAlignment="Center" VerticalAlignment="Center" Template="{DynamicResource Foo}">Foo</Button>
        <Label x:Name="labelBar" Grid.Column="1"  HorizontalAlignment="Center" VerticalAlignment="Center" Background="{Binding ElementName=border, Path=Background}">Bar</Label>
    </Grid>
</Page>

Doesn’t find the element named “border” in the ControlTemplate, but changing ElementName in labelBar’s binding to “buttonFoo” makes the Background Green, as expected.

Leave a Comment