【问题标题】:Databind properties of a class in ContentViewContentView 中类的数据绑定属性
【发布时间】:2021-04-27 16:37:53
【问题描述】:

我正在努力实现我认为可能很简单的目标,但由于我是 Xamarin 和数据绑定的新手,我想我正在经历一场风暴。 我有一个非常简单的ContentPage,它只有一个数据绑定到我的视图模型,用于这个页面和我的ContentView,TotalsTemplate。

<ContentPage.BindingContext>
    <vm:DealsTodayViewModel />
</ContentPage.BindingContext>
<ContentPage.Content>
    <StackLayout>
        <template:TotalsTemplate></template:TotalsTemplate>
    </StackLayout>
</ContentPage.Content>

我的视图模型有一个我的类的公共属性 Totals,它具有基本的 int、string、decimal 属性。

    public class DealsTodayViewModel
    {
        Public string ViewModelPeriod;
        public PeriodTotals Totals;
        public DealsTodayViewModel()
        {
            ViewModelPeriod = "TODAY";
            Totals = new PeriodTotals
            {
                Period = "DAILY",
                ClientServices_Deals_Chicago = 1,
                ClientServices_Deals_Manchester_Na = 1,
                ClientServices_Deals_Manchester_Uk = 1,
                ClientServices_Ramp_Chicago = 1.2m,
                ClientServices_Ramp_Manchester_Na = 1.3m,
                ClientServices_Ramp_Manchester_Uk = 1.4m
        };
    }
}

现在在我的TotalsTemplte ContentView 我有一个Grid 里面有以下内容。

    <Label Text="{***Binding ViewModelPeriod***}" FontAttributes="Bold"/>
    <Frame OutlineColor="Black" Grid.Row="0" Grid.Column="1">
        <Label Text="{Binding ***Totals.Period***}" FontAttributes="Bold"/>
    </Frame>

DealsTodayViewModel 上的 String 属性在我的 ContentView 中可见,但在我的 Totals 属性中看不到 Perod 属性,我是否错误地绑定到此?

【问题讨论】:

  • 您只能绑定到公共属性Totals 不是 C# 属性
  • Totals 是 PeriodTotals 类型的公共属性,我的基础类 Jason?
  • 请查找 C# 属性的定义
  • 什么是总计?
  • 不,它是一个字段。一个属性将有一个 get/set

标签: xaml xamarin xamarin.forms data-binding


【解决方案1】:

document开始,数据绑定应该绑定properties而不是字段:

数据绑定是链接两个对象的属性的技术,因此 一个属性的变化会自动反映在另一个属性中 财产。数据绑定是模型-视图-视图模型的一个组成部分 (MVVM) 应用架构。

因此解决方案是将虚拟机中的字段更改为属性:

public class DealsTodayViewModel
{
    public string ViewModelPeriod { get; set; }
    public PeriodTotals Totals { get; set; }
    public DealsTodayViewModel()
    {
        ...
    }
}

参考:field and property

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 2021-02-21
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多