私はPrism/WPFプロジェクトでこのようなViewModelクラスを持っています。DelegateCommandのCanExecuteアクションの操作
public class ContentViewModel : ViewModelBase, IContentViewModel
{
public ContentViewModel(IPersonService personService)
{
Person = personService.GetPerson();
SaveCommand = new DelegateCommand(Save, CanSave);
}
public Person Person { get; set; }
public DelegateCommand SaveCommand { get; set; }
private void Save()
{
// Save actions here...
}
private bool CanSave()
{
return Person.Error == null;
}
}
次のように上記のViewModelに使用者タイプが定義されている:
public class Person : INotifyPropertyChanged, IDataErrorInfo
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged("FirstName");
}
}
// other properties are implemented in the same way as above...
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private string _error;
public string Error
{
get
{
return _error;
}
}
public string this[string columnName]
{
get
{
_error = null;
switch (columnName)
{
// logic here to validate columns...
}
return _error;
}
}
}
ContentViewModelのインスタンスがビューのDataContextのように設定されています。
<TextBox Text="{Binding Person.FirstName, ValidatesOnDataErrors=True}" />
<Button Content="Save" Command="{Binding SaveCommand}" />
私はViewModelにコマンドハンドラの変化を見ることができました姓のような人のプロパティにバインドさ、[保存]をクリックしているテキストボックスに変更を加えた場合:ビュー内私は次のように人への結合を使用しました。しかし、これらのプロパティのいずれかが検証に失敗した場合、CanSaveは実行されず、ボタンが無効になることはありません。
上記のシナリオでは、DelegateCommandのCanExecuteアクションハンドラに基づいてボタンを無効にするにはどうすればよいですか?
問題はOnPropertyChangedがエラーが変更されたときには呼び出されません。 +1 – Raj