执行命令后,按钮将被禁用

时间:2017-11-15 04:05:40

标签: c# wpf xaml

有时单击事件后按钮(完成)将被禁用。

我还必须再次点击该表单才能重新启用该按钮。

这是我的代码:

Button behavior

XAML:

<Button
    Grid.Column="1"
    Height="20"
    Margin="10,5"
    Command="{Binding DoneCommand}"
    Content="Done" />

C#:

private readonly RaiseCommand doneCommand;
private readonly BackgroundWorker worker;

private object _currentUserState;
private int _currentProgress;

public RaiseCommand DoneCommand
{
    get { return doneCommand; }
}

public MainWindowViewModel()
{
    doneCommand = new RaiseCommand(o => worker.RunWorkerAsync(), o => !worker.IsBusy);

    worker = new BackgroundWorker();
    worker.DoWork += DoDoneCommand;
    worker.ProgressChanged += ProgressChanged;
    worker.RunWorkerCompleted += RunWorkerCompleted;
    worker.WorkerReportsProgress = true;
}

private void DoDoneCommand(object sender, DoWorkEventArgs e)
{
    MessageBox.Show("test");
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    CurrentUserState = e.UserState;
    CurrentProgress = e.ProgressPercentage;
}

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{

}

修改

我的命令类。

这个类正在处理我的XAML命令。

它实现了ICommand接口。

public class RaiseCommand : ICommand
{
    readonly Action<object> _action;
    readonly Func<object, bool> _canExecute;

    public RaiseCommand(Action<object> execute) : this(execute, null) { }

    public RaiseCommand(Action<object> execute, Func<object, bool> canExecute)
    {
        _action = execute ?? throw new ArgumentNullException("execute");
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以在CommandManager.InvalidateRequerySuggested()方法中调用RunWorkerCompleted方法强制CommandManager刷新所有命令的状态:

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    CommandManager.InvalidateRequerySuggested();
}

或者你可以使用ICommand实现提供一种方法来引发CanExecuteChanged事件,例如Prism的DelegateCommand或MvvmLight的RelayCommand。