在视图上有不同的按钮,如何在执行命令时控制按钮的IsEnabled状态?
如果我执行此命令:
public ICommand DoSomethingCommand
{
get
{
if (doSomethingCommand == null)
{
doSomethingCommand = new RelayCommand(
(parameter) =>
{
this.IsBusy = true;
this.someService.DoSomething(
(b, m) =>
{
this.IsBusy = false;
}
);
},
(parameter) => !this.IsBusy);
}
return this.doSomethingCommand ;
}
}
我设置了触发OnPropertyChanged事件的IsBusy属性。所有其他按钮在其命令的CanExecute中检查此属性。但是,执行上述命令时,按钮不会被禁用。
我该怎么做?
答案 0 :(得分:0)
需要触发CanExecuteChanged以便命令源知道调用CanExecute。
执行此操作的一种简单方法是调用CommandManager.InvalidateRequerySuggested()
。
bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set
{
if (value == _isBusy)
return;
_isBusy = value;
//NotifyPropertyChanged("IsBusy"); // uncomment if IsBusy is also a Dependency Property
System.Windows.Input.CommandManager.InvalidateRequerySuggested();
}
}
答案 1 :(得分:0)
为什么不在自己的自定义版本的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" />