2
2

More than 3 years have passed since last update.

Caliburn.Microを用いてWPFアプリケーションを作成する(4)

Last updated at Posted at 2020-06-14

Buttonを追加し、挙動を設定する

概要

WPF in C# with MVVM using Caliburn Microの54分目あたりからを参考に、前回のComboBox追加の内容に、Buttonを追加する。

完成形

ボタンを押すとテキストボックスがクリアされるようにする。

image.png

実装

今回も動画を見ながら進める。

ViewにButtonを追加する

とりあえずShellViewに次のようにボタンを追加する。

ShellView.xaml(抜粋)
        <!-- row 4 -->
        <Button Grid.Row="4" Grid.Column="1" >Clear</Button>

ShellViewに実行時の関数を追加する

ShellViewModel.cs(抜粋)
        public void ClearText()
        {
            FirstName = "";
            LastName = "";
        }

この内容をViewに反映するため、さきほどのxamlを書き換える。

ClearText呼び出しを追加

ボタンを押すとTextBoxに紐づけられたFirstName, LastNameが""に設定されるので、結果として紐づけられたTextBoxの内容が空欄になる。

        <Button Grid.Row="4" Grid.Column="1"  x:Name="ClearText">Clear</Button>

内容が入っている時だけクリアされる条件をつける

CanClearTextを実装する。
(動画参照 1:05:00付近)

まだ理解がおいついてないが、なんらかの命令規則(バリデーション?)によって動いてる模様。(→2020.6.15追記)
xamlを変更してないが、ClearTextに対してCanClearTextを追加するだけで、挙動が変わる(ちょっとびっくりした)

いずれかのTextBoxに値があるときだけEnableになる条件

ShellViewModel.cs
        public bool CanClearText(string firstName, string lastName)
        {
            // throw new NotImplementedException();
            return !String.IsNullOrWhiteSpace(firstName) && !String.IsNullOrWhiteSpace(lastName);
        }
        public void ClearText(string firstName, string lastName)
        {
            FirstName = "";
            LastName = "";
        }

完成

値が入っているときにClearボタンを押すと、TextBoxが空欄になる。

追記

Canほげほげについて、どこに説明があるのかとCaliburn.Microのドキュメントを頑張って読んでみたら、なんのことはない一番先頭のIntroductionに書かれてた(おぢさんなので見つけたときは「(爆)」とか言いたくなったorz)

Can~はActionMessageという機構になっている。
さらにイベントトリガになる Action Conventions という規約も存在しているみたいなので、あとで真面目に読む。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2