びおりんのブログ

きままにアプリのできるまでを公開していきます

WPFのMVVMで電卓づくり(4)

電卓の数字ボタンを押したら出力画面が更新される仕組みを作成します

今回はボタンクリックに紐づけしたコマンドに渡されるパラメーターを用いて
電卓の出力画面用の内部データを更新します

下準備

下図はソリューションエクスプローラーの構成です
f:id:kazoojapan1985:20200503010317p:plain

前回までで下記ファイルを作成済みです

  • App.xaml
  • DelegateCommand.cs
  • MainView.xaml
  • MainViewModel.cs

今回はMainModel.csを追加していきます

電卓ボタンに登録したコマンドパラメーターを引数に
出力画面に表示させる文字列であるDisplayTextを設定する
SetText()を含むクラスをMainModel.csに作成します

   class MainModel
    {
        public string DisplayText { get; private set; }

        public void SetText(string str)
        {
            if ((str.Equals("0") || str.Equals("00"))
             && string.IsNullOrEmpty(this.DisplayText))
            {
                return;
            }
            this.DisplayText += str;
        }
    }

ボタンクリックで出力画面用の内部データを更新させる

数字ボタンをクリックすることで呼び出されるMainViewModel.PushCommandから
出力画面に表示させる文字列を格納するMainModel.SetText()を呼び出します

   class MainViewModel
    {
        public string DisplayText { get; set; }
        public ICommand PushCommand { get; set; }

        public MainViewModel()
        {
            var model = new MainModel();
            this.PushCommand = new DelegateCommand(
                param => 
                {
                    MessageBox.Show(param?.ToString() ?? string.Empty);
                    if (param == null) { return; }
                    var str = param.ToString();
                    if (int.TryParse(str, out int num))
                    {
                        model.SetText(str);
                    }
                },
                param =>
                {
                    return true;
                });
        }
    }

上のコードでは、MainViewModelのコンストラクタにてMainModelを生成し
MainViewModel.PushCommand実行時に参照できるようにしています
またPushCommand.Execute()にてMainModel.SetText()を呼び出しています

動作確認

MainModel.SetText()にブレークポイントを設定しておきます
数字ボタンをクリックするとMainModel.SetText()に到達することを確認できます
f:id:kazoojapan1985:20200503164802p:plain