首页 > 解决方案 > 绑定:未找到属性。MVVM

问题描述

我正在尝试将视图页面中视图的属性绑定到我在名为 ViewModel 的地毯中拥有的类,然后从名为 Model 的地毯中的另一个名为计算器(模型)的类的实例中我试图访问属性包含在那里,问题是它似乎不起作用;在输出部分,我收到以下消息:Binding: 'N2' property not found on 'XamForms.ViewModel.MainPageViewModel'。其中 N2 是模型类“计算器”的属性。我将在代码中详细解释它:

MainPage.xaml 代码:

<Entry
    x:Name="n1"
    Text="{Binding calculator.N1}"
></Entry>
<Entry
    x:Name="n2"
    Text="{Binding calculator.N2}"
></Entry>
<Button
    BackgroundColor="LimeGreen"
    Command="{Binding Operations}"
></Button>

正如您将看到的,与 Operations 的绑定有效,因为它在 ViewModelPage 中而不是在计算器(模型)中。

MainPage.xaml.cs 代码:

public MainPage()
{
    MainPageViewModel mainPageViewModel = new MainPageViewModel();
    this.BindingContext = mainPageViewModel;
}

MainPageViewModel 代码:

class MainPageViewModel
{
    public Command Operations { get; set; }
    public Calculator calculator;
    public MainPageViewModel()
    {
        Operations = new Command(DoOperations);
        calculator = new Calculator();
    }

    private void DoOperations()
    {
        calculator.Division = calculator.N1 / calculator.N2;
        //Here is where I get the message, N1 and N2 are null, but they should have the values that I 
        //inserted on the entry, the binding to Division is also incorrect.
    }
}

计算器(型号)代码:

class Calculator : INotifyPropertyChanged
{

private decimal n1;
public decimal N1
{
    get
    {
        return n1;
    }
    set
    {
        n1 = Convert.ToDecimal(value);
    }
}

private decimal n2;
public decimal N2
{
    get
    {
        return n2;
    }
    set
    {
        n2 = Convert.ToDecimal(value);
    }
}

private decimal division;
public decimal Division
{
    get
    {
        return division;
    }
    set
    {
        division= Convert.ToDecimal(value);
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

我正在研究 Xamarin Forms 和 MVVM,所以这可能是一个简单的错误,但我找不到它,而且我发现的所有相关解决方案对于我的实际水平来说都太复杂了,所以我无法推断它们。如果您需要更多信息,我会在看到后立即提供,感谢您的宝贵时间,祝您有美好的一天。

标签: c#mvvmxamarin.formsdata-binding

解决方案


Operations 的绑定有效,因为它被声明为属性(使用 getter 和 setter):public Command Operations { get; set; }

public Calculator calculator;是一个简单的字段。绑定不支持字段。使其成为一个属性

public Calculator calculator { get; set; }

推荐阅读