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

前端之家收集整理的这篇文章主要介绍了xaml – x中ElementName的替代:与DataTemplates绑定前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用传统的{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访问控件之外的用户控件属性的唯一真正方法是使用标准绑定机制.

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

原文链接:https://www.f2er.com/windows/364474.html

猜你在找的Windows相关文章