看法:
使用 WPF(MVVM) 玩一个基本的计算器。我有 1 个文本框用于第一个数字,1 个文本框用于第二个数字,1 个文本块用于结果和 1 个按钮来执行 AddCommand 并返回结果。将这些控件绑定到正确数据的正确 XAML 语法是什么。
模型:
public class Operation : INotifyPropertyChanged
{
private double _result;
public Operation()
{
_result = 0;
}
public double Result
{
get { return _result; }
set
{
if (value != _result)
{
_result = value;
RaisePropertyChanged("Result");
}
}
}
public double DoAdd(double first, double second)
{
_result = first + second;
return _result;
}
}
视图模型:
public class CalcViewModel
{
private Operation _operation;
public RelayCommand AddCommand { get; set; }
public CalcViewModel()
{
_operation = new Operation();
// This is not correct, how to define the AddCommand here so it takes two params
// The first and second nums to work with.
AddCommand = new RelayCommand(first, second => ExecuteAddCommand(first, second));
}
private void ExecuteAddCommand(double first, double second)
{
// How to bind this returned double to the TextBlock in View
_oepration.DoAdd(first, second);
}
}
应 Vlad 的要求编辑新版本的代码
模型:
public class Operation
{
private double _result;
public Operation()
{
_result = 0;
}
public double Result
{
get { return _result; }
}
public void PerformAdd(double leftNum, double rightNum)
{
_result = leftNum + rightNum;
}
}
视图模型:
public class CalcViewModel
{
private Operation _operation;
public double LeftNumber { get; set; }
public double RightNumber { get; set; }
public double Result { get; set; }
public RelayCommand AddCommand { get; set; }
public CalcViewModel()
{
AddCommand = new RelayCommand(a => ExecuteAddCommand());
_operation = new Operation();
}
private void ExecuteAddCommand()
{
_operation.PerformAdd(LeftNumber, RightNumber);
Result = _operation.Result;
}
查看 XAML:
<TextBox Text="{Binding LeftNumber}" />
<TextBox Text="{Binding RightNumber}" />
<TextBox Text="{Binding Result}" />
<Button Content="Add" Command="{Binding AddCommand}" />
查看后面的代码:
public partial class CalcUserControl : UserControl
{
CalcViewModel vm;
public CalcUserControl()
{
InitializeComponent();
vm = new CalcViewModel();
this.DataContext = vm;
}
}
我尝试了所有绑定模式,但没有任何结果。我这里还有一个问题,在这种情况下,默认绑定模式是什么?
我什至认为它与计算的数据类型有关,所以我从 double 切换到 int,但仍然无法正常工作。