繁体   English   中英

绑定:未找到属性。 MVVM

[英]Binding: Property not found. 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,所以这可能是一个简单的错误,但我找不到它,而且我发现的所有相关解决方案对于我的实际水平来说都太复杂了,所以我无法推断它们。 如果您需要更多信息,我会在看到后立即提供,谢谢您的时间,祝您有美好的一天。

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

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

public Calculator calculator { get; set; }

在属性 N1 和 N2 的模型“计算器”中,您需要在属性的设置部分调用“OnPropertyChanged”。

前任:

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

您需要将 Calculator 类设为“public”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM