RelayCommand
の目的は、ボタンコントロールが必要とするインターフェイスを実装し、ViewModelのすぐ隣にある一般的な機能にコールを渡すことです。
だから例えば、あなたのようなのViewModelクラスを持っているでしょう:あなたのコントロールで
class HelloWorldViewModel : ViewModelBase
{
public RelayCommand DisplayMessageCommand { get; private set; }
private DispatchTimer _timer;
public HelloWorldViewModel()
{
this.DisplayMessageCommand = new RelayCommand(this.DisplayMessage, CanDisplayMessage);
// Create a timer to go off once a minute to call RaiseCanExecuteChanged
_timer = new DispatchTimer();
_timer = dispatcherTimer.Tick += OnTimerTick;
_timer.Interval = new Timespan(0, 1, 0);
_timer.Start();
}
private void OnTimerTick(object sender, EventArgs e)
{
this.DisplayMessageCommand.RaiseCanExecuteChanged();
}
public bool CanDisplayMessage()
{
return DateTime.Now.Minute % 2 == 0;
}
public void DisplayMessage()
{
//TODO: Do code here to display your message to the user
}
}
を、あなたはどちらかDataContext={StaticResource ...}
あなたを通して直接XAMLの背後にあるかのコードでDataContext
セットを持っているでしょうボタンは、ViewModelのコマンドにバインドします。
<Button Content='Push me' Command='{Binding DisplayMessageCommand}' />
ボタンをクリックすると、DisplayMessageCommand
このオブジェクトのExecute()
を呼び出します。RelayCommand
は、DisplayMessage
メソッドに転送します。
DispatchTimer
は1分に1回オフになり、RaiseCanExecuteChanged()
を呼び出します。これにより、コマンドにバインドされているボタンがコマンドがまだ有効かどうかを再確認することができます。それ以外の場合は、ボタンをクリックしてコマンドが現在使用できないことを確認します。
グレートと!それをクリアしてくれてありがとう! – Evan
ちょうど好奇心から、コマンドのCanDisplayMessage()をIsEnabledプロパティにバインドする方法はありますか? – Evan
@evan、ボタンのIsEnabledプロパティを意味する場合は?これは、ボタンのCommandオブジェクトを設定すると自動的に行われます。 – MerickOWA