采用MvvmLight工具构建的计算器
Models:CalculationModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MvvmCalculator.Models
{
public class CalculationModel
{
#region 私有成员
private string _result;
#endregion
#region 构造函数
public CalculationModel()
{
FirstOperand = string.Empty;
SecondOperand = string.Empty;
Operation = string.Empty;
_result = string.Empty;
}
#endregion
#region 公共属性和方法
public string FirstOperand { get; set; } //第一个数
public string SecondOperand { get; set; } //第二个数
public string Operation { get; set; } //运算符
public string Result { get { return _result; } } //结果
public void CalculateResult() //计算结果
{
ValidateData(); //校验数据
try
{
switch (Operation) //利用运算符,决定使用哪种算法
{
case ("+"):
_result = (Convert.ToDouble(FirstOperand) + Convert.ToDouble(SecondOperand)).ToString();
break;
case ("-"):
_result = (Convert.ToDouble(FirstOperand) - Convert.ToDouble(SecondOperand)).ToString();
break;
case ("*"):
_result = (Convert.ToDouble(FirstOperand) * Convert.ToDouble(SecondOperand)).ToString();
break;
case ("/"):
_result = (Convert.ToDouble(FirstOperand) / Convert.ToDouble(SecondOperand)).ToString();
break;
case ("sin"):
_result = Math.Sin(DegreeToRadian(Convert.ToDouble(FirstOperand))).ToString();
break;
case ("cos"):
_result = Math.Cos(DegreeToRadian(Convert.ToDouble(FirstOperand))).ToString();
break;
case ("tan"):
_result = Math.Tan(DegreeToRadian(Convert.ToDouble(FirstOperand))).ToString();
break;
}
}
catch (Exception)
{
_result = "Error whilst calculating";
throw;
}
}
private double DegreeToRadian(double angle) //角度运算
{
return Math.PI * angle / 180.0;
}
private void ValidateOperand(string operand) //校验数据
{
try
{
Convert.ToDouble(operand);
}
catch (Exception)
{
_result = "Invalid number: " + operand;
throw;
}
}
private void ValidateOperation(string operation) //校验运算符
{
switch (operation)
{
case "/":
case "*":
case "-":
case "+":
case "tan":
case "cos":
case "sin":
break;
default:
_result = "Unknown operation: " + operation;
throw new ArgumentException("Unknown Operation: " + operation, "operation");
}
}
private void ValidateData() //校验所有数据
{
switch (Operation)
{
case "/":
case "*":
case "-":
case "+":
ValidateOperand(FirstOperand);
ValidateOperand(SecondOperand);
break;
case "tan":
case "cos":
case "sin":
ValidateOperand(FirstOperand);
break;
default:
_result = "Unknown operation: " + Operation;
throw new ArgumentException("Unknown Operation: " + Operation, "operation");
}
}
#endregion
}
}
ViewModels:CalculatorViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MvvmCalculator.Mod