在《 Visual C# 2010 从入门到精通》的例子中有个计算器的应用程序---Maths Operators
里面用到了几个新的控件,在这里作一下记录,并讲讲自己多这个应用程序的理解:
RadioButton 和 StackPanel
正题:
StackPanel用来摆放RadioButton
RadioButton用来作选择,单击选中.
如下图:
if ((bool)addition.IsChecked)
addValues();
else if ((bool)subtraction.IsChecked)
subtractValues();
else if ((bool)multiplication.IsChecked)
multiplyValues();
else if ((bool)division.IsChecked)
divideValues();
else if ((bool)remainder.IsChecked)
remainderValues();
用来判断RadioButton是否选中.
这是整体程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MathsOperators
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void calculateClick(object sender, RoutedEventArgs e)
{
try
{
if ((bool)addition.IsChecked)
addValues();
else if ((bool)subtraction.IsChecked)
subtractValues();
else if ((bool)multiplication.IsChecked)
multiplyValues();
else if ((bool)division.IsChecked)
divideValues();
else if ((bool)remainder.IsChecked)
remainderValues();
if (!((bool)addition.IsChecked || (bool)subtraction.IsChecked || (bool)multiplication.IsChecked
|| (bool)division.IsChecked || (bool)remainder.IsChecked))
{
expression.Text = "请选择运算法则!";
}
}
catch (Exception caught)
{
expression.Text = "异常!!!";
result.Text = caught.Message;
}
}
private void addValues()
{
int lhs = int.Parse(lhsOperand.Text);
int rhs = int.Parse(rhsOperand.Text);
int outcome;
outcome = lhs + rhs;
expression.Text = lhsOperand.Text + " + " + rhsOperand.Text;
result.Text = outcome.ToString();
}
private void subtractValues()
{
int lhs = int.Parse(lhsOperand.Text);
int rhs = int.Parse(rhsOperand.Text);
int outcome;
outcome = lhs - rhs;
expression.Text = lhsOperand.Text + " - " + rhsOperand.Text;
result.Text = outcome.ToString();
}
private void multiplyValues()
{
int lhs = int.Parse(lhsOperand.Text);
int rhs = int.Parse(rhsOperand.Text);
int outcome;
outcome = lhs * rhs;
expression.Text = lhsOperand.Text + " * " + rhsOperand.Text;
result.Text = outcome.ToString();
}
private void divideValues()
{
int lhs = int.Parse(lhsOperand.Text);
int rhs = int.Parse(rhsOperand.Text);
int outcome;
outcome = lhs / rhs;
expression.Text = lhsOperand.Text + " / " + rhsOperand.Text;
result.Text = outcome.ToString();
}
private void remainderValues()
{
int lhs = int.Parse(lhsOperand.Text);
int rhs = int.Parse(rhsOperand.Text);
int outcome;
outcome = lhs % rhs;
expression.Text = lhsOperand.Text + " % " + rhsOperand.Text;
result.Text = outcome.ToString();
}
private void quitClick(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
流程是判断哪种预算法则来进行相应的运算服务程序.
try 和catch来扑捉异常!!!