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

xaml – x中ElementName的替代:与DataTemplates绑定

发布时间:2020-12-14 04:23:41 所属栏目:Windows 来源:网络整理
导读:使用传统的{Binding}语法时,您可以指定元素名称以指向页面上的特定控件,并能够访问其属性.例如,如果页面被命名为页面,您可以执行以下操作: {Binding ElementName=Page,Path=Name} 它说的是{x:Bind}语法 With x:Bind,you do not need to use ElementName=xxx
使用传统的{Binding}语法时,您可以指定元素名称以指向页面上的特定控件,并能够访问其属性.例如,如果页面被命名为页面,您可以执行以下操作:
{Binding ElementName=Page,Path=Name}

它说的是{x:Bind}语法

With x:Bind,you do not need to use ElementName=xxx as part of the
binding expression. With x:Bind,you can use the name of the element
as the first part of the path for the binding because named elements
become fields within the page or user control that represents the root
binding source.

因此,对于{x:Bind}中的上述示例,将是

{x:Bind page.Name}

哪个工作正常,直到它在数据模板内(例如ListView的ItemTemplate).在这种情况下,它不再起作用,因为它在指定的数据类型上查找Page会导致以下错误(假设我的数据类型是customer):

XamlCompiler error WMC1110: Invalid binding path ‘Page.Name’ :
Property ‘Page’ can’t be found on type ‘Customer’

将{x:Bind}语法与数据模板和数据模板外部的访问控制一起使用的解决方案是什么?

示例代码可用here(注意具体提交)

据我所知,此时无法使用x:bind方法直接绑定到控件的属性,因为它不支持其绑定定义中的元素名称.

这并不意味着你不能绑定到dataTemplate中的控件,你仍然可以做这样的事情来访问控件,但你只是无法使用编译的绑定x:Bind语法.

<DataTemplate x:DataType="local:Customer">
     <StackPanel Orientation="Vertical">
         <Button Content="{Binding Name,ElementName=page}" />
         <TextBlock Text="{x:Bind Title}" />
     </StackPanel>        
 </DataTemplate>

您获得错误的原因是数据模板为其数据源提供父级的方式. x:绑定绑定不能引用控件对象,而Customer类型执行Page.Name属性或路径.如上所示,仅使用XAML访问控件之外的用户控件属性的唯一真正方法是使用标准绑定机制.

我希望这回答了你的问题.

(编辑:李大同)

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

    推荐文章
      热点阅读