使用 C#写一下WPF框架的计算器
时间: 2024-09-28 22:08:51 浏览: 75
创建一个基本的Windows Presentation Foundation (WPF)计算器,首先需要设置XAML布局来设计用户界面,然后编写C#代码来处理计算逻辑。以下是一个简单的步骤示例:
1. **创建项目**:
- 打开Visual Studio,选择“文件” > “新建” > “项目”,选择“WPF App (.NET Framework)”模板。
2. **设计用户界面 (XAML)**:
在`App.xaml`(资源视图)中添加一个`Grid`作为主容器,并包含数字按钮、运算符按钮和结果标签等元素。例如:
```xml
<Window x:Class="CalculatorApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<TextBlock Text="0" Margin="5"/>
<TextBox x:Name="Display" Height="40" Width="150" />
<!-- 数字按钮... -->
<!-- 运算符按钮... -->
</StackPanel>
</Window>
```
3. **处理事件和逻辑 (C#)**:
创建一个新的类`CalculationLogic.cs`来处理点击事件和计算:
```csharp
public partial class MainWindow : Window
{
private double _currentNumber = 0;
private string _operator = "";
public MainWindow()
{
InitializeComponent();
Display.Text = "0";
}
// 示例:处理数字按钮点击
private void NumberButton_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
Display.Text += button.Content.ToString();
}
// 示例:处理运算符按钮点击
private void OperatorButton_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
_operator = button.Content.ToString();
if (_operator != "=")
{
try
{
_currentNumber = Convert.ToDouble(Display.Text);
Display.Text = "";
}
catch (FormatException)
{
Display.Text = "Invalid input";
}
}
}
// 示例:处理等于按钮点击,进行计算
private void EqualButton_Click(object sender, RoutedEventArgs e)
{
double result;
if (_operator == "")
{
result = Convert.ToDouble(Display.Text);
}
else
{
result = PerformMathOperation(_currentNumber, _operator);
_currentNumber = result;
}
Display.Text = result.ToString();
}
private double PerformMathOperation(double firstOperand, string operatorString)
{
switch (operatorString)
{
case "+":
return firstOperand + _currentNumber;
case "-":
return firstOperand - _currentNumber;
case "*":
return firstOperand * _currentNumber;
case "/":
return firstOperand / _currentNumber;
}
throw new ArgumentException($"Unsupported operator: {operatorString}");
}
}
```
以上只是一个基础版本,您可以根据需求添加更多的功能,如历史记录、清除按钮、小数点等。记得给每个按钮添加适当的`Click`事件处理器。
阅读全文