[英]Xamarin Forms bind to parent property in DataTemplate
I am having trouble binding to a property in Xamarin, and can't figure it out using Microsoft's documentation for some reason.我无法绑定到 Xamarin 中的属性,并且由于某种原因无法使用 Microsoft 的文档来解决。
Say I have this viewmodel:假设我有这个视图模型:
public class FooViewModel
{
public IEnumerable<string> Foos { get; set; }
public string SpecialFoo { get; set; }
}
And this in my view:在我看来,这是:
<StackLayout BindableLayout.ItemsSource="{Binding Foos}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding SpecialFoo}"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
I am running into the problem that in the DataTemplate, I can't make the binding to a property inside FooViewModel.我遇到了在 DataTemplate 中无法绑定到 FooViewModel 中的属性的问题。 How do I make this binding to SpecialFoo?
如何将此绑定到 SpecialFoo?
That's easy all you need is a reference to your page and tell it that look for this in the VM and not in the model:这很简单,您只需要引用您的页面并告诉它在 VM 中而不是在 model 中查找此内容:
Give your current ContentPage a name:为您当前的 ContentPage 命名:
<ContentPage
...
x:Name="currentPage"/>
Then your label would look something like:然后你的 label 看起来像:
<Label Text="{Binding BindingContext.SpecialFoo, Source={x:Reference currentPage}}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.