Livet の ViewModelCommand.RaiseCanExecuteChanged
Livet の Command クラス、ViewModelCommand で CanExecuteChanged メソッドが呼ばれるタイミングが判らないとのコメントを頂きました。
プロパティの状態によってコマンドの有効・無効を制御したいなら、セッター内で ViewModelCommand.RaiseCanExecuteChanged をコールすればいいです。
以下、簡単なサンプル用意しました。Livet のバージョンは0.99、TextBox と Button だけのプログラムです。TextBox が空なら Button は無効、一文字でも入力されると、Button は有効になります。
ViewModel
まず ViewModel。OKCommand の CanExecute メソッドでは、Text プロパティが空もしくはヌル以外なら True を返すよう設定します。
次に、Text プロパティのセッター内で OKCommand の RaiseCanExecuteChanged メソッドをコールします。RaiseCanExecuteChanged メソッドが実行されると、CanOK コマンドが呼び出されます。
Option Explicit On Option Strict On Public Class MainWindowViewModel Inherits ViewModel #Region "Text変更通知プロパティ" Private _Text As String Public Property Text() As String Get Return _Text End Get Set(ByVal value As String) If (_Text = value) Then Return _Text = value RaisePropertyChanged("Text") ' コマンドが実行可能かどうかが変化したことを通知します。 Me.OKCommand.RaiseCanExecuteChanged() End Set End Property #End Region #Region "OKCommand" Private _OKCommand As ViewModelCommand Public ReadOnly Property OKCommand() As ViewModelCommand Get If _OKCommand Is Nothing Then _OKCommand = New ViewModelCommand(AddressOf OK, AddressOf CanOK) End If Return _OKCommand End Get End Property Private Function CanOK() As Boolean Return Not String.IsNullOrEmpty(Me.Text) End Function Private Sub OK() MessageBox.Show("OK") End Sub #End Region End Class
View
View は以下のとおり、通知プロパティとコマンドをバインドしてるだけです。
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" xmlns:l="http://schemas.livet-mvvm.net/2011/wpf" xmlns:local="clr-namespace:LivetWPFApplication1" Title="MainWindow" Height="150" Width="200"> <Window.DataContext> <local:MainWindowViewModel /> </Window.DataContext> <Grid> <TextBox Margin="0,20,0,0" VerticalAlignment="Top" Width="120" Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}" /> <Button Content="OK" Margin="0,60,0,0" VerticalAlignment="Top" Width="65" Command="{Binding Path=OKCommand}" /> </Grid> </Window>
実行するとこうなる。
お粗末さまでした。<(_ _)>