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
- 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); } } } }
- 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>
- 実行すると・・・なぜかデフォルト値の50が表示される。
TextBlockのTextプロパティにText="{Binding Count}"
とか書いていないのに、なぜ???
これはCariburn.Microが、Nameと同じプロパティ名を、自動的にバインドしてくれる。
Handling events
- ViewModelにIncrementCountメソッドを追加する。
// <ShellViewModel.cs> public void IncrementCount() { Count++; }
- 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>
- 実行して"Up"ボタンを押すと・・・なぜかCountがインクリメントされる。
CommandバインディングとかInteractionTrigger~CallMethodActionとか書いていないのに、になぜ???
これはCariburn.Microが、Nameと同じメソッドを、自動的に呼び出してくれる。
(Buttonの場合はClickイベント、別なイベントにする書式もある)
Event guards (CanExecuteみたいな)
- ViewModelにCanIncrementCountメソッドを追加する。
// <ShellViewModel.cs> public bool CanIncrementCount { get { return Count < 100; } }
- ViewModelのCountプロパティのセッターに変更通知を追加
public int Count { get { return _count; } set { _count = value; NotifyOfPropertyChange(() => Count); NotifyOfPropertyChange(() => CanIncrementCount); // <<=この行を追加 } }
- 実行して"Up"ボタンを押し続けCountが100になると・・・なぜか[Up]ボタンが押せなくなる。
もう変な説明はいらないね、、、そういうことです。