gpt4 book ai didi

wpf - x :Reference and ElementName? 和有什么区别

转载 作者:行者123 更新时间:2023-12-02 02:18:36 25 4
gpt4 key购买 nike

根据x:Reference Markup Extension MSDN 页面,x:Reference

References an instance that is declared elsewhere in XAML markup. The reference refers to an element's x:Name.

根据Binding.ElementName Property MSDN 页面,ElementName

The value of the Name property or x:Name Directive of the element of interest.

回顾第一页的备注部分:

x:Reference and WPF

In WPF and XAML 2006, element references are addressed by the framework-level feature of ElementName binding. For most WPF applications and scenarios, ElementName binding should still be used. Exceptions to this general guidance might include cases where there are data context or other scoping considerations that make data binding impractical and where markup compilation is not involved.

为了完整起见,以下是 ElementName 页面上备注部分的一部分:

This property is useful when you want to bind to the property of another element in your application. For example, if you want to use a Slider to control the height of another control in your application, or if you want to bind the Content of your control to the SelectedValue property of your ListBox control.

现在,虽然我完全了​​解何时以及如何使用 ElementName 属性,但我并不完全理解它与 x:Reference 标记之间的区别扩大。任何人都可以解释一下这一点,特别是扩展 x:Reference 备注部分中显示的最后一句话吗?:

Exceptions to this general guidance might include cases where there are data context or other scoping considerations that make data binding impractical and where markup compilation is not involved.

最佳答案

基本上就像你说的那样,两者的作用几乎相同。然而,在幕后却存在着细微的差异。

{x:Reference ...} -> 仅返回对象的引用,它不会像绑定(bind)那样在两个属性之间创建“桥梁”。在这一切的背后,正在使用一个服务来在特定范围(通常是窗口本身)中搜索给定名称。

{Binding ElementName="..."} -> 首先,它创建该绑定(bind)对象,然后搜索对象名称,但不使用与 x 相同的技术:引用。搜索算法在 VisualTree 中向上和/或向下移动以找到所需的元素。因此,始终需要一个功能性的 VisualTree。例如,当在非 UiElement 内部使用时,它将不起作用。最后,Binding 留下来并做它的日常工作。

这行不通:

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

这有效:

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

有点像这样:)

关于wpf - x :Reference and ElementName? 和有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19244111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com