Xamarin Forms绑定到DataTemplate中的父属性



我在Xamarin中绑定属性时遇到问题,由于某种原因,无法使用Microsoft文档解决。

假设我有这个视图模型:

public class FooViewModel
{
public IEnumerable<string> Foos { get; set; }
public string SpecialFoo { get; set; }
}

在我看来:

<StackLayout BindableLayout.ItemsSource="{Binding Foos}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding SpecialFoo}"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>

我遇到了一个问题,即在DataTemplate中,我无法绑定到FooViewModel中的属性。如何将此绑定到SpecialFoo?

这很简单,你只需要一个页面的引用,并告诉它在VM中而不是在模型中查找:

为您当前的ContentPage命名:

<ContentPage 
...
x:Name="currentPage"/>

然后你的标签会看起来像:

<Label Text="{Binding BindingContext.SpecialFoo, Source={x:Reference currentPage}}"/>

最新更新