びおりんのブログ

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

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

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

今回は数字ボタンクリックで更新された内部データを
電卓の出力画面に反映させます

内部データの出力画面へのバトンタッチ(Model⇒ViewModel⇒View)

数字ボタンクリックで更新されたMainModel.DisplayTextを
MainViewModel.DisplayTextに代入します
MainViewModel.DisplayTextをRaisePropertyChangedイベントで
MainView.xaml上の出力画面であるTextBlockに反映させます

Model⇒ViewModel

MainViewModel.PushCommand.Execute()に登録したラムダ式にて
MainModel.SetText()を呼び出して更新したMainModel.DisplayTextを
MainViewModel.DeisplayTextに代入する処理を追加します

           this.PushCommand = new DelegateCommand(
                param => 
                {
                    if (param == null) { return; }
                    var str = param.ToString();
                    if (int.TryParse(str, out int num))
                    {
                        model.SetText(str);
                    }
                    this.DisplayText = model.DisplayText;
                },
                param =>
                {
                    return true;
                });

ViewModel⇒View

MainViewModelにINotifyPropertyChangedインターフェースを実装し
MainModel.DisplayText代入後のMainViewModel.DisplayTextを引数にして
RaisePropertyChangedイベントを着火します

   class MainViewModel : INotifyPropertyChanged
    {
        public string DisplayText { get; set; }

        public ICommand PushCommand { get; set; }
        public MainViewModel()
        {
            var model = new MainModel();
            this.PushCommand = new DelegateCommand(
                param => 
                {
                    if (param == null) { return; }
                    var str = param.ToString();
                    if (int.TryParse(str, out int num))
                    {
                        model.SetText(str);
                    }
                    this.DisplayText = model.DisplayText;
                    var args = new PropertyChangedEventArgs(nameof(this.DisplayText));
                    PropertyChanged(this, args);
                },
                param =>
                {
                    return true;
                });
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

MainView.xamlにおいて、出力画面であるTextBlockにDisplayTextを紐づけします

        <!--出力画面-->
        <TextBlock Grid.ColumnSpan="6" Text="{Binding Path=DisplayText}"/>

動作確認

数字ボタンを「1」「9」「00」の順にクリックすると
出力画面に「1900」と表示されます
f:id:kazoojapan1985:20200503181824p:plain