我在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;
}
}
在上述视图模型中所用的人类型定义如下:
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}" />
当我做它绑定到人的属性,如名字,然后点击保存,我可以看到在视图模型命令处理程序的变化而变化,以文本框:里面查看如下我用结合的人。但是,如果这些属性中的任何一个在验证失败CanSave永远不会执行,并且按钮永远不会被禁用。
如何在上述场景中禁用基于DelegateCommand的CanExecute动作处理程序的按钮?
你遇到的问题是,OnPropertyChanged是当错误改变时不被调用。 +1 – Raj 2012-03-15 16:36:06