wpf简易计算器的MainWindow类
时间: 2023-06-19 16:05:37 浏览: 92
wpf 简易计算器
以下是一个简易计算器的WPF应用程序中的MainWindow类示例:
```csharp
using System;
using System.Windows;
using System.Windows.Controls;
namespace Calculator
{
public partial class MainWindow : Window
{
private double num1, num2, result;
private string operation;
public MainWindow()
{
InitializeComponent();
}
private void NumberButton_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
if (operation == null)
{
num1 = num1 * 10 + Convert.ToDouble(button.Content.ToString());
ResultLabel.Content = num1;
}
else
{
num2 = num2 * 10 + Convert.ToDouble(button.Content.ToString());
ResultLabel.Content = num2;
}
}
private void OperationButton_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
operation = button.Content.ToString();
}
private void EqualsButton_Click(object sender, RoutedEventArgs e)
{
switch (operation)
{
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
ResultLabel.Content = result;
num1 = result;
num2 = 0;
operation = null;
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
num1 = 0;
num2 = 0;
operation = null;
ResultLabel.Content = "0";
}
}
}
```
该类包含了按钮点击事件的处理程序,用于处理数字、运算符和清除按钮的点击。通过使用num1、num2和operation变量来追踪计算器的状态。当数字按钮被点击时,它们被添加到num1或num2中,当运算符按钮被点击时,它们被设置为operation变量,当等号按钮被点击时,通过执行适当的操作计算结果。最后,当清除按钮被点击时,计算器被复位。
阅读全文