漫坊亭

社会の底辺プログラマ

Caliburn Micro Part 2: Data Binding and Events をやってみる。

Mindscape Blog » Blog Archive » Caliburn Micro Part 2: Data Binding and Events manbou404.hatenablog.com

要は、Binding, Command(Execute,CanExecute)のお気楽な書き方。

以下は、前回のソリューションをつかう。

Data binding

  1. ViewModelにCountプロパティを追加する。
// <ShellViewModel.cs>
using Caliburn.Micro;

namespace Tutorial
{
    public class ShellViewModel  : PropertyChangedBase, IShell
    {
        private int _count = 50;

        public int Count
        {
            get { return _count; }
            set
            {
                _count = value;
                NotifyOfPropertyChange(() => Count);
            }
        }
    }
}
  1. Viewにテキストブロックを追加する
<!--ShellView.xmal-->
<UserControl x:Class="Tutorial.ShellView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid MinWidth="300" MinHeight="300" Background="LightBlue">
        <TextBlock Name="Count" Margin="20" FontSize="150" 
                   VerticalAlignment="Center" 
                   HorizontalAlignment="Center" />
    </Grid>

</UserControl>
  1. 実行すると・・・なぜかデフォルト値の50が表示される。

f:id:jfactory:20150625131125p:plain

TextBlockのTextプロパティにText="{Binding Count}"とか書いていないのに、なぜ???
これはCariburn.Microが、Nameと同じプロパティ名を、自動的にバインドしてくれる。

Handling events

  1. ViewModelにIncrementCountメソッドを追加する。
// <ShellViewModel.cs>
public void IncrementCount()
{
  Count++;
}
  1. Viewにボタンを追加する
<!--ShellView.xmal-->
<Grid MinWidth="300" MinHeight="300" Background="LightBlue">
  <RepeatButton Name="IncrementCount" Content="Up" Margin="15" VerticalAlignment="Top" />
  <TextBlock Name="Count" FontSize="150" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>
  1. 実行して"Up"ボタンを押すと・・・なぜかCountがインクリメントされる。

f:id:jfactory:20150625132418p:plain

CommandバインディングとかInteractionTrigger~CallMethodActionとか書いていないのに、になぜ???
これはCariburn.Microが、Nameと同じメソッドを、自動的に呼び出してくれる。
(Buttonの場合はClickイベント、別なイベントにする書式もある)

Event guards (CanExecuteみたいな)

  1. ViewModelにCanIncrementCountメソッドを追加する。
// <ShellViewModel.cs>
public bool CanIncrementCount
{
  get { return Count < 100; }
}
  1. ViewModelのCountプロパティのセッターに変更通知を追加
        public int Count {
            get { return _count; }
            set {
                _count = value;
                NotifyOfPropertyChange(() => Count);
                NotifyOfPropertyChange(() => CanIncrementCount);  // <<=この行を追加
            }
        }
  1. 実行して"Up"ボタンを押し続けCountが100になると・・・なぜか[Up]ボタンが押せなくなる。

f:id:jfactory:20150625133745p:plain

もう変な説明はいらないね、、、そういうことです。

ソース一式