例如我为 WP7 做计算器。
这是我的简单逻辑类:
public class CalcLogic
{
public static double Calculate(double a, double b, string operation)
{
double res = 0;
switch (operation)
{
case ("+"):
res = a + b;
break;
case ("-"):
res = a - b;
break;
case ("*"):
res = a * b;
break;
case ("/"):
res = a / b;
break;
default: break;
}
return res;
}
}
这是在我的 MainPage.xaml.cs 中:
private const int Rows = 4, Cols = 4;
private string[,] buttonTags = { { "7", "8", "9", "/" },
{ "4", "5", "6", "*" },
{ "1", "2", "3", "-" },
{ "0", "C", "=", "+" }
};
private Button[,] buttons;
// Constructor
public MainPage()
{
InitializeComponent();
CreateButtons();
}
public void CreateButtons()
{
buttons = new Button[Rows, Cols];
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Cols; j++)
{
buttons[i, j] = new Button();
buttons[i, j].Content = buttonTags[j, i];
buttons[i, j].Width = 120;
buttons[i, j].Height = 110;
buttons[i, j].Margin = new Thickness(i * 110 + 5, j * 110 + 100, 0, 0);
buttons[i, j].VerticalAlignment = System.Windows.VerticalAlignment.Top;
buttons[i, j].HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
buttons[i, j].Name = "button" + buttonTags[j, i];
buttons[i, j].Click += new System.Windows.RoutedEventHandler(Button_Click);
ContentPanel.Children.Add(buttons[i, j]);
ContentPanel.UpdateLayout();
}
}
}
问题是 - Button_Click 方法的正确性如何?
private void Button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
tbResult.Text += button.Content.ToString();
string operation = "";
double a = 0;
double b = 0;
if (button.Content.ToString() == "=")
{
tbResult.Text = CalcLogic.Calculate(a, b, operation).ToString();
}
if (button.Content.ToString() == "C")
{
tbResult.Text = "";
}
...
}
也许我应该只写我的 TextBox 数字并签名,然后解析?但我认为这不是正确的算法。
升级版:
我就是这样做的,效果很好。但我不确定正确的实现:
private void Button_Click(object sender, EventArgs e)
{
try
{
Button button = sender as Button;
double res;
if (Double.TryParse(button.Content.ToString(), out res))
{
DigitClick(button.Content.ToString());
}
else
{
OperatorClick(button.Content.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
ClearAll();
}
}
private void ClearAll()
{
first = second = result = 0;
operStr = "";
newNum = true;
tbResult.Text = "";
}
private void DigitClick(string dig)
{
if (newNum)
{
tbResult.Text = "";
}
tbResult.Text += dig;
newNum = false;
}
private void OperatorClick(string oper)
{
if (oper == "=")
{
if (operStr == "=" || operStr == "")
{
return;
}
second = Convert.ToInt32(tbResult.Text);
result = CalcLogic.Calculate(first, second, operStr);
tbResult.Text = result.ToString();
operStr = oper;
}
else if (oper == "C")
{
ClearAll();
}
else
{
operStr = oper;
first = Convert.ToInt32(tbResult.Text);
}
newNum = true;
}
我只是想知道 GUI 计算器的最佳实现,谢谢。