加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

WPF Binding ElementName方式无效的解决方法--x:Reference绑定

发布时间:2020-12-14 04:38:16 所属栏目:大数据 来源:网络整理
导读:需求: 背景:Grid的有一个TextBlock name:T1和一个ListBox,ListBox中有两个TextBlock name:T2,T3 要求:T2的前景色绑定到T1的前景色上(其他属性同理)T3的前景色绑定到T2上 下面的代码去掉了所有不必要的内容,仅保留了两种绑定方式 Path Path.ToolTip

需求:

背景:Grid的有一个TextBlock name:T1和一个ListBox,ListBox中有两个TextBlock name:T2,T3

要求:T2的前景色绑定到T1的前景色上(其他属性同理)T3的前景色绑定到T2上

下面的代码去掉了所有不必要的内容,仅保留了两种绑定方式

<Path>
    <Path.ToolTip>
        <ToolTip>
            <StackPanel>
                <TextBlock Name="TipsTitle"/>
                <ListBox>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Name="temp_series" 
                                Foreground="{Binding Source={x:Reference Name=TipsTitle},Path=Foreground}"/>
                                <TextBlock 
                                Foreground="{Binding ElementName=temp_series,Path=Foreground}"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </ToolTip>
    </Path.ToolTip>
</Path>

x:Reference 是 XAML 2009 中引入的功能,也算是比较早的功能了;ElementName 是 XAML 一开始出现便开始有的功能。二者在使用时在感觉上是比较相似的,但多数情况下都更有优势。

本文将解释 x:Reference。

典型的使用 x:Reference 的例子是:

<object property="{x:Reference instancexName}" .../>
其中, instancexName 是另一个用 x:Name 指定名称的元素。

x:Reference 前面带了一个 x 命名空间前缀,所以可想而知这是与 x:Name 类似的 XAML 编译相关的标记。

在微软官方文档中描述为:

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.
用中文来描述就是说:以前在 XAML 2006 的时候,使用 ElementName 在绑定中获得对应到元素的绑定源,而这能适用于大多数情况。不过,如果绑定上下文中拥有不同的命名边界,那么这时使用 ElementName 可能无法找到绑定源。这时可以使用 x:Reference 替代。

你可以阅读 WPF 的 ElementName 在 ContextMenu 中无法绑定成功?试试使用 x:Reference! - walterlv 了解 x:Reference 替代 ElementName 解决绑定中命名边界的问题。

另外, ElementName 是在运行时通过查找可视化树或逻辑树来确定名称边界(NameScope)的,所以一定程度上性能也不那么好。

https://www.codercto.com/a/31458.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读