What is the difference between x:Reference and ElementName?

后端 未结 2 1790
余生分开走
余生分开走 2020-11-27 12:29

According to the x:Reference Markup Extension page on MSDN, x:Reference

References an instance that is declared elsewhere in XAML markup. Th

相关标签:
2条回答
  • 2020-11-27 13:21

    Basically like you said those two do almost the same. However there are small differences under the hood.

    {x:Reference ...} -> returns just a reference of an object it doesn't create that "bridge" between two properties like binding would do. Behind all that a service is being used that searches for the given name in a specific scope which is usually the window itself.

    {Binding ElementName="..." } -> first of all it creates that binding object then it searches for the object name but not by using the same technique under the hood as x:Reference. The search algorithm moves up and/or down in VisualTree to find the desired element. Therefore a functional VisualTree is always needed. As example when used inside a Non-UiElement, it won't work. In the end the Binding stays and does its daily bread.

    This won't work:

    <StackPanel>
     <Button x:name="bttn1" Visibility="Hidden">Click me</Button>
     <DataGrid>
      <DataGrid.Columns>
        <DataGridTextColumn Visibility="{Binding ElementName=bttn1, Path=DataContext.Visibility}"/>
     ....
    

    This works:

    <StackPanel>
     <Button x:name="bttn1" Visibility="Hidden">Click me</Button>
     <DataGrid>
      <DataGrid.Columns>
        <DataGridTextColumn Visibility="{Binding Source={x:Reference bttn1}, Path=DataContext.Visibility}"/>
     ....
    

    Sort of like that :)

    0 讨论(0)
  • 2020-11-27 13:22

    ElementName is platform specific. I.e. it may or may not be present based on which platform you're using. x:Reference elevates that concept to a XAML native feature. Thus any platform that supports XAML supports x:Reference.

    0 讨论(0)
提交回复
热议问题