c# - 绑定:未找到属性。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,所以这可能是一个简单的错误,但我找不到它,而且我发现的所有相关解决方案对于我的实际水平来说都太复杂了,所以我无法推断它们。如果您需要更多信息,我会在看到后立即提供,感谢您的宝贵时间,祝您有美好的一天。
解决方案
Operations 的绑定有效,因为它被声明为属性(使用 getter 和 setter):public Command Operations { get; set; }
public Calculator calculator;
是一个简单的字段。绑定不支持字段。使其成为一个属性:
public Calculator calculator { get; set; }
推荐阅读
- php - 如何在php中获取字符串“tag=”之后的数字
- c# - 当输出参数返回不同的派生类型时,NSubstitute 抛出 ArgumentSetWithIncompatibleValueException
- scala - 不能证明 "a Tuple2" <:< (T, U)
- r - 在 facet_wrap/facet_grid 对象的每一帧上显示数据点的问题
- sql - SQL如何计算订单购买之间的平均时间?(根据下一行和上一行进行sql计算)
- javascript - 如何在 for 循环中对具有精确索引的元素重复迭代?
- php - 将包含文件添加到 wordpress/woocomerce 网站以显示在产品页面上
- javascript - 当我全屏显示 div 时,如何确保其中的对象也全屏显示?
- c++ - Matlab 类多个访问器用于相同的数据
- docker - 如何从 docker 容器中检索文件?