using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; namespace SimpleCalculator; public partial class CalculatorMV : ObservableObject { private enum State { Number, Action, Calculate, } private enum Action { None, Add, Subtract, Multiply, Divide, } private State currentState = State.Number; private string accumulator = "0"; private (Action, string) currentAction = (Action.None, "0"); private bool isDecimal = false; private bool isNegative = false; [ObservableProperty] private string resultText = "0"; [RelayCommand] private void numberClicked(string value) { if (this.currentState == State.Action) { this.ResultText = "0"; } if (value == "0" && this.ResultText == "0") return; if (this.ResultText == "0") this.ResultText = ""; else if (this.ResultText == "-0") this.ResultText = "-"; this.currentState = State.Number; this.ResultText += value; } [RelayCommand] private void acClicked() { this.accumulator = ""; this.currentState = State.Number; this.currentAction = (Action.None, ""); this.isDecimal = false; this.isNegative = false; this.ResultText = "0"; } [RelayCommand] private void invertClicked() { if (this.isNegative) { this.isNegative = false; this.ResultText = this.ResultText.Substring(1); } else { this.isNegative = true; this.ResultText = "-" + this.ResultText; } } [RelayCommand] private void percentileClicked() { this.accumulator = this.ResultText; this.accumulator = (double.Parse(this.accumulator) * 0.01).ToString(); this.ResultText = this.accumulator; } [RelayCommand] private void divideClicked() { var value = this.ResultText; this.currentAction = (Action.Divide, value); this.accumulator = "0"; this.currentState = State.Action; } [RelayCommand] private void multiplyClicked() { var value =this.ResultText; this.currentAction = (Action.Multiply, value); this.accumulator = "0"; this.currentState = State.Action; } [RelayCommand] private void subtractClicked() { var value = this.ResultText; this.currentAction = (Action.Subtract, value); this.accumulator = "0"; this.currentState = State.Action; } [RelayCommand] private void addClicked() { var value = this.ResultText; this.currentAction = (Action.Add, value); this.accumulator = "0"; this.currentState = State.Action; } [RelayCommand] private void equalClicked() { var (action, value) = this.currentAction; switch (action) { case Action.None: break; case Action.Add: this.accumulator = (double.Parse(value) + double.Parse(this.ResultText)).ToString(); break; case Action.Subtract: this.accumulator = (double.Parse(value) - double.Parse(this.ResultText)).ToString(); break; case Action.Multiply: this.accumulator = (double.Parse(value) * double.Parse(this.ResultText)).ToString(); break; case Action.Divide: this.accumulator = (double.Parse(value) / double.Parse(this.ResultText)).ToString(); break; } this.ResultText = this.accumulator.ToString(); this.currentState = State.Calculate; } [RelayCommand] private void decimalPointClicked() { this.isDecimal = true; this.ResultText += ","; } }