Sometimes design time data just won’t show, even though everything works at runtime. This is quite normal since Expression Blend, and the Visual Studio designer for that matter don’t instantiate our views and ViewModels in the context of an application.

MefedMVVM has a concept of design time data using the IDesignTimeAware interface, so we can provide an implementation of our ViewModel purely for use by the designers.

In my current case, despite having all my bindings correct, and things working at runtime, Blend refuses to show me the design time ListBoxItems…

So like all things code-FAIL related, we debug, simply set a break point on the DesignTimeInitialization method and attach to Expression Blend.

You will need to close and re-open the Xaml View (or do a build) so Blend re-initialises our ViewModel… and viola! We now know what the problem is.

In my case it was simply a service which was missing at design time. Allowing defaults allows the design time composition to succeed since we don’t actually need it until runtime.

Initially the project started out as a quick hack together to enable a single piece of functionality. However as functionality is growing its time for the codebase to grow up too, and this includes the UI elements. I’ve decided to use MefedMVVM for its design time blend features and easy to grok codebase.

If you try and use it out of the box with your MEF Component and debug, you might get the following error:

Marquee controls have been around for a long time and have been abused for much of that time. Their place in the user experience should really be very small, since they have a number of drawbacks – information isn’t static for the user to absorb, they typically only display a limited amount of information and they assume a certain reading speed (which may be too slow or too fast). Nevertheless, there are times when marquee controls are useful, news or stock tickers for example.

So I needed a marquee to display a news ticker in Silverlight, and I didn’t want to have use any nasty code-behind. Nothing seemed entirely appropriate, so I used the marquee control from Jobi Joy as a starting point and extended it:

The control needed to work in an MVVM application. This meant that it mustn't rely on code calling “ticker.StartAnimation()” or anything like that – it had to all work by binding to a view model.

I changed the animation so that there is always as much content visible as possible, i.e. the first bit of content starts at the left-hand side, not at the right-hand side

Just for kicks, I added a little bit of acceleration to the scrolling, so that it is not always a constant speed

I got the marquee working in WPF as well as Silverlight

Some friends contributed here too – Marcin extracted the control template into generic.xaml, and Marlon fixed an issue where the marquee would zoom uncomfortably fast if there was too much content. The result is that you can just use a few lines of XAML to achieve the effect:

The result should show up below, if you have Silverlight 4 installed on your machine.

The full source code and samples in WPF and Silverlight can be found in the SharpFellows Toolkit. And just for practice I used the Reactive Framework in the sample to asynchronously download and display some news headlines from a website. Enjoy!

Programming applications for Windows has always been and event-driven affair: we’d place a control on a form, attach an event handler to it and whack some code behind to handle it. Job done. Unfortunately this approach is not very testable and as you’ve probably gathered by now, we’re very much interested in testability around here. There are couple of possible solutions to this problem and one of them (which works particularly well in WPF) is to replace event handlers with commands. This allows the view to be loosely coupled to the underlying “view model” and Darius Collins blogged about this approach using delegate WPF commands. There is also an excellent article by Josh Smith available on MSDN which discusses this pattern (Model-View-ViewModel) in detail.

To cut the long story short, the version of self-updateable DelegateCommand<T> (or RelayCommand<T> as Josh Smith calls it) is now part of the Sharpfellows.Toolkit but as it is being discussed extensively in the posts I have already mentioned I will not repeat myself here. Having said that, I feel I need to mention a minor deficiency of the UpdateableCommand<T> (as we call it): there are sadly some rare cases when the command does not work as expected when it comes to enabling/disabling the associated UI element. This is simply due to the RequerySuggested event is being raised in rather mysterious circumstances when the command manager “thinks” something may require refresh. This may not always work well with your app, so you may need to call CommandManager.InvalidaterequerySuggested() method to force it. Luckily the behaviour is repeatable and easy to spot so you do not have to worry about the app working erratically.

Asynchronous command

As it often happens, in order to keep the UI responsive, some of the commands need to execute the handler on a background thread. This is usually done using BackgroundWorker which provides convenient completion callback executing on the UI thread. There are however two major problems with this approach: first of all the threading code creates unnecessary and repeatable noise, cluttering the view model with “how” rather than letting it focus on the “what”, and secondly the multithreading introduces serious complexity into unit tests of the view model. To solve both of those issues I came up with UpdateableAsyncCommand<T> which, as the name implies, is capable of executing the command asynchronously. The clever bit about it is the fact that instead of directly using the threading API to execute the handler, the async command delegates the task of executing it to an object implementing IThreadingService interface (see below).

1: /// <summary>

2: /// Provides facilities for background tasks

3: /// </summary>

4: publicinterface IThreadingService

5: {

6: /// <summary>

7: /// Queues the execution of a task

8: /// </summary>

9: /// <param name="work"></param>

10: void QueueExecution(Action work);

11:

12: /// <summary>

13: /// Queues the execution of a task and calls back when it is complete

14: /// </summary>

15: /// <param name="work"></param>

16: /// <param name="completionCallback"></param>

17: void QueueExecution(Action work, Action completionCallback);

18:

19: /// <summary>

20: /// Queues the execution of a task with callback for successful completion and failure

You may be wondering why on earth would we introduce an abstraction to be put on top of relatively simple threading API, but the reasons become clear when it comes to unit testing. UpdateableAsyncCommand<T> allows us to inject it with an implementation of the IThreadingService which executes the method synchronously. This fake implementation (provided for your convenience in the form of SynchronousThreadingService) allows the unit tests to run synchronously and shifts their focus to the business flow and interaction of components, rather than obscuring the picture with complex synchronisation code. The async command exposes IsBusy property which is set to true whenever the command handler is executing. As the UpdateableAsyncCommand<T> implements INotifyPropertyChanged you can even use the IsBusy property to drive the state of your UI. The following code fragment illustrates the most important aspects of the UpdateableAsyncCommand<T>

68: /// Gets or sets a value indicating whether this instance is busy.

69: /// </summary>

70: /// <value><c>true</c> if this instance is busy; otherwise, <c>false</c>.</value>

71: publicbool IsBusy

72: {

73: get { return _isBusy; }

74: private set

75: {

76: if (_isBusy == value)

77: return;

78:

79: _isBusy = value;

80: // As the IsBusy may be set from the background thread, we ned to "poke" the

81: // command manager to let it know it may be a good idea to check the command's CanExecute

82: CommandManager.InvalidateRequerySuggested();

83: OnPropertyChanged(() => IsBusy);

84: }

85: }

86:

87: privatevoid CommandFinished()

88: {

89: _completionCallback();

90: IsBusy = false;

91: }

92:

93: privatevoid CommandError(Exception ex)

94: {

95: _errorCallback(ex);

96: IsBusy = false;

97: }

98: }

More on the IThreadingService

The contract for the threading service is quite similar to that of IScheduler (found in reactive extensions) and for a while I was thinking if we should not use it instead. It became clear however that more often than not we need to call back to UI thread when the command handler is finished. This in turn forces use of SynchronisationContext, which is not available when running unit tests on the background thread (as some test runners do). As already mentioned we use SynchronousThreadingService in unit tests which alleviates the need to use SynchronizationContextaltogether.

The concept of the IThreadingService has one more benefit: as the service is usually injected by an IoC container, it is very easy to switch from asynchronous to synchronous execution mode simply by replacing the implementation. This may be very helpful when debugging an application when we suspect the issue may be caused a misbehaving thread.

PS: To pay credit where it is due, I feel I need to mention that the threading service code included in the toolkit has been authored by John Rayner. The original idea however came from Dave Hanson who since then patented it and made enough money in royalties to leave his job and embark on a year long journey across Australia :)

Putting it all together

To illustrate the use of asynchronous commands I developed a simple (and rather silly) Web search application called Bingo. The app uses Microsoft’s Bing engine API and the search, as you would expect, is being executed using async command. For what it is, the sample may seem seriously over-engineered but I wanted to illustrate how the async command fits into the big picture of MVVM application.

As you can see from the screenshot above, in spite of all the years spent mastering Microsoft technologies, our website still does not deserve #1 spot in the Bing search results for “sharpfellows”… How disappointing ;)