Вам нужно помочь WPF узнать, что состояние исполняемой команды изменилось. Простой способ сделать это:
CommandManager.InvalidateRequerySuggested()
внутри CanExecuteThread:
set
{
_threadStopped = value;
CommandManager.InvalidateRequerySuggested()
}
РЕДАКТИРОВАТЬ (теперь, когда у меня есть время): реальная проблема, скорее всего, в том, что вы не уведомляете об изменении свойства CanExecuteThread
. Он должен поднять PropertyChanged
, чтобы WPF обнаружил изменение:
public bool CanExecuteThread
{
get { return _threadStopped; }
set
{
if (_threadStopped != value)
{
_threadStopped = value;
this.OnPropertyChanged(() => this.CanExecuteThread);
}
}
}
Выше предполагается, что ваш базовый класс ViewModel
имеет метод OnPropertyChanged
.
Тем не менее, я также хотел отметить, что вы могли бы упростить вещи, просто используя BackgroundWorker
:
public class WindowViewModel : ViewModel
{
private readonly BackgroundWorker backgroundWorker;
public WindowVieWModel()
{
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
// do work here (what's currently in ThreadMethod)
};
backgroundWorker.RunWorkerCompleted += delegate
{
// this will all run on the UI thread after the work is done
this.OnPropertyChanged(() => this.CanExecuteThread);
};
}
...
public bool CanExecuteThread
{
get { !this.backgroundWorker.IsBusy; }
}
private void ExecuteThread(object p)
{
// this will kick off the work
this.backgroundWorker.RunWorkerAsync();
// this property will have changed because the worker is busy
this.OnPropertyChanged(() => this.CanExecuteThread);
}
}
Вы можете изменить этот код, чтобы сделать его еще лучше, но вы поняли.