Saturday 11 December 2010

MVVM RelayCommands and BackgroundWorker

This is largely cribbed from elsewhere, but I wanted to have a system where a RelayCommand starts off an asynchronous update of the Model.

First we have to have a flag to hold the idle status
public bool IsIdle ( get; set; }
The RelayCommand command needs to bind its CanExecute to this property

_getCommandData = new RelayCommand (
() => GetTimeSheet(),
() => IsIdle);

This means that the WPF item bound to this command (in this case a button), is disabled when the idle status is set to false.

So in order to use this, and to not bung up the main UI thread, we need to run the command in a BackgroundWorker thread

protected void DoWork(Action work)
{
idle = false;
var worker = new BackgroundWorker();
worker.DoWork += (sender, e) => work();
worker.RunWorkerCompleted += (sender, e) => Idle = true;
worker.RunWorkerAsync();
}

public void GetTimeSheet()
{
DoWork (delegate() {
_model.GetTimeSheet();
TimeSheetData = _model.TimeSheetData;
});
}