【问题标题】:Xamarin Forms bind to parent property in DataTemplateXamarin Forms 绑定到 DataTemplate 中的父属性
【发布时间】:2020-04-17 09:13:00
【问题描述】:

我在绑定到 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?

【问题讨论】:

    标签: c# xamarin xamarin.forms


    【解决方案1】:

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

    为您当前的 ContentPage 命名:

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

    那么您的标签将类似于:

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

    【讨论】:

    • 我的英雄!这让我整个上午都发疯了,谢谢。
    • 乐于助人:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2018-09-09
    • 2016-12-30
    • 2018-09-30
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多