xaml - x :Bind with DataTemplates 中 ElementName 的替代品

标签 xaml binding windows-store-apps winrt-xaml xbind

使用传统的 {Binding} 语法时,您可以指定元素名称以指向页面上的特定控件,并能够访问其属性。例如,如果页面名为 page你可以这样做:

{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 方法直接绑定(bind)到控件的属性,因为它不支持其绑定(bind)定义中的元素名称。

这并不意味着您不能绑定(bind)到 dataTemplate 中的控件,您仍然可以执行类似的操作来访问控件,但您只是无法使用已编译的绑定(bind) x:Bind 语法。

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

您收到错误的原因是由于数据模板父数据源的方式。 x:Bind 绑定(bind)不能引用控件对象,并且您的 Customer 类型具有 Page.Name 属性或路径。如上所示,仅使用 XAML 访问控件之外的用户控件属性的唯一真正方法是求助于标准绑定(bind)机制。

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

关于xaml - x :Bind with DataTemplates 中 ElementName 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32849864/

相关文章:

silverlight - 在 Silverlight/WinRT 中仅使用 XAML 将元素定位在 Canvas 内的中心(而不是左上角)

c# - UWP - 以编程方式在 ItemTemplate 中显示进度条

wpf - x :Key is ignored inside MergedDictionaries

c# - 如何覆盖 .NET 4 中动态对象的 PropertyDescriptor.GetValue 和 PropertyDescriptor.SetValue

c# - 如何通过异步方法有效地更新 UI?

c# - 如果以前的记录在 ItemsSource 集合中没有匹配项,则 WPF ComboBox 绑定(bind)有效,如果有则失败

.net - 绑定(bind)到转换器参数

c# - 如何将 ContextMenuStrip 添加到 ToolStripMenuItem

c# - SQLite 数据库插入错误约束

c# - Blend for Visual Studio 2012 设计 View 不起作用