Binding ElementName. Does it use Visual Tree or Logical Tree

旧街凉风 提交于 2019-11-27 11:57:15

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.

The ElementName property of a binding in a sense (see below answer) works off of the logical tree because one is using ElementName to divine a specific control solely on the logical tree in the Xaml.

will it lookup visual or logical tree?

The premise you propose is wrong, there is no lookup per-se on either tree. One is simply setting a Source property for reflection operation used by the binding instead of defaulting to the inherited DataContext of the logical tree.

If one reads the documentation of Binding.ElementName Property (System.Windows.Data) (bolding mine):

"...the ElementName property is one of the ways you can explicitly set the source of a Binding and override the inherited data context."

The source is any instantiated object which is within the current operations namespace which can be accessed and reflected off of.

No more no less and most likely will be in the Logical Tree (but doesn't have too) because people name there logical items in Xaml, but also could be in the visual tree.


See Data Binding Overview for more info.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!