c# - 绑定(bind) : Property not found. MVVM

标签 c# mvvm xamarin.forms data-binding

我正在尝试将 View 页面中 View 的属性绑定(bind)到我在名为 ViewModel 的地毯中拥有的类,然后从名为 Model 的地毯中的另一个名为计算器(模型)的类的实例中,我试图访问属性包含在那里,问题是它似乎不起作用;在输出部分,我收到以下消息:绑定(bind):在“XamForms.ViewModel.MainPageViewModel”上找不到“N2”属性 .其中 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 的绑定(bind)有效,因为它在 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,所以这可能是一个简单的错误,但我找不到它,而且我发现的所有相关解决方案对于我的实际水平来说都太复杂了,所以我无法推断它们。
如果您需要更多信息,我会在看到后立即提供,感谢您的时间,祝您有美好的一天。

最佳答案

Operations 的绑定(bind)有效,因为它被声明为属性(带有 getter 和 setter):public Command Operations { get; set; }public Calculator calculator;是一个简单的领域。绑定(bind)不支持字段。使其成为一个属性:

public Calculator calculator { get; set; }

关于c# - 绑定(bind) : Property not found. MVVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59528844/

相关文章:

c# - 如何使用单声道在 mac 控制台上编译单个 c# 文件?

c# - 将集合绑定(bind)到 Ninject

c# - 反射权限异常

ios - 如何在 Xamarin.iOS 中保护 cache.db 文件

xaml - 使用 StringFormat、xamarin.forms 在 9 位绑定(bind)号码之间添加空格

c# - 如何在 MySQL Entity Framework 中执行过程

c# - 从 .NET 程序集透明地访问 native 内存

c# - Linq:分组依据,根据变量(例如枚举)对结果进行不同的分组

mvvm - 设置UWP组合框的SelectedItem

ios - 构建 iOS 项目时出现 errSecInternalComponent 错误