为什么不在您自己的 RelayCommand 类的自定义版本上实现 INotifyPropertyChanged。这将符合 MVVM:
public class RelayCommand : ICommand, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly Action execute;
private readonly Func<bool> canExecute;
private bool isBusy;
public bool IsBusy
{
get { return isBusy; }
set
{
isBusy = value;
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("IsBusy"));
}
}
}
public event EventHandler CanExecuteChanged
{
add
{
if (this.canExecute != null)
{
CommandManager.RequerySuggested += value;
}
}
remove
{
if (this.canExecute != null)
{
CommandManager.RequerySuggested -= value;
}
}
}
public RelayCommand(Action execute) : this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.execute = execute;
this.canExecute = canExecute;
}
public void Execute(object parameter)
{
this.IsBusy = true;
this.execute();
this.IsBusy = false;
}
public bool CanExecute(object parameter)
{
return this.canExecute == null ? true : this.canExecute();
}
}
然后使用这样的命令:
<Button Command="{Binding Path=DoSomethingCommand}"
IsEnabled="{Binding Path=DoSomethingcommand.IsBusy,
Converter={StaticResource reverseBoolConverter}}"
Content="Do It" />