If you are used to works with Winform, you probably feel being less productive in WPF, but this can be overtaken by approaching the design the correct way, and with proper tools productivity would be the same as Winform, and probably better. MVVM seems to be the right pattern to cleanup the scaring and messy stuff polluting the XAML and the code behind on the view. There is some framework to help to do this, and I choose Caliburn for this sample application, but I think the idea is the important part, so let’s try and compare. By the way, it worked for me trying to write my own MVVM framework, this increase the learning curve gradient when we go for another more proven and stable solution. If you want follow this suggestion you probably would look at this very famous video about MVVM, edited by the author of Caliburn, Rob Eisenberg. Rob is a man that look at the mess in the XAML and said: Ok let’s create something to clean up this, instead of start up again with a WinForm app . So let’s talk about the app, should be simple but doing something interesting, and must take 1/2 hour to write. I decided to write a Flickr picture browser so there is as well some async call to web services to show.
Let’s prepare our toolbelt for start we need to:
So start the application and put the required dependencies in the Lib folder of the solution, so we have something like this at the end:
All this reference are dependencies of our app, and with this we are ready to start to write the application itself. We start to “bootstrapping” the application. We have a main window for our application, and this will be our application main View, and we need to stick to it a ViewModel. Caliburn can do this automatically in the boostrap phase, lets see.
First create a class deriving from Botstrapper<T> where T is our ViewModel. As below:
This class can be empty to start, we come back later, now we modify the App.Xaml markup, by removing the StartupUri and adding a bootstrapper instance as a resource, so an instance will born:
<Setter Property="TextOptions.TextFormattingMode" Value="Display"/>
If we launch the application at this point, the main window appear anyway, why ?
Because Caliburn infer the main window to start from the view model class name. The default convention is that the view has the same type name as the model minus “Model”, so if our model is MainWindowModel, the view to launch is MainWindow. So what happened in the boot was:
ViewModelBinder-INFO:Binding FlickAndFlock.MainWindow and FlickAndFlock.MainWindowModel.Action-INFO:Setting DC of FlickAndFlock.MainWindow to FlickAndFlock.MainWindowModel.Action-INFO:Attaching message handler FlickAndFlock.MainWindowModel to FlickAndFlock.MainWindow.
As I can see in my trace output in Visual Studio after having set up the log in the boot class static constructor:
LogManager.GetLog = t => GetLogger(t);
We overwritten the function GetLog of LogManager with our one, returning an instance of a class implementing ILog that just dump the messages on the trace. Having a log enabled is a good idea when we have a convention over configuration based framework. Sometimes we don’t understand why convention are not applied as we expect, and usually we can guess where the problem is by looking at the log. Another point here is how we change the log recovering strategy: by setting a function to a property. This way of customization is cross used in the entire Caliburn framework. So as you probably guessed, if we want to change the way we look for the view from the model name, the strategy is exactly the same:
ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>…
In the example application we used the default one, but is good to know that if does not feet our convention, we can change.
So now we have the main view,and the main ViewModel, but what exactly we can put inside the ViewModel ? Well we can think the ViewModel as a model oriented to the presentation, focalized on the view, not on the business logic. Is the ViewModel to that is notified about the UI events, ie the “Actions” the user want to do.
We proceed now to add some user control on the XAML to allow the user to search by tag the Flicker photo database, obtaining something like:
<TextBox Margin="20" x:Name="Tags"></TextBox>
<Button Margin="30,20,30,20" IsDefault="True" x:Name="Search">Search Flickr</Button>
<Button Margin="10,10,10,10" Width="80" x:Name="PrevPage">Previous</Button>
<Button Margin="10,10,10,10" Width="80" x:Name="NextPage">Next</Button>
The XAML is quite simple, there is nothing related to events in it, but, as you can see from the picture, previous and next are disabled, and search is not. This is another Caliburn magic, let see what’s in the log:
ViewModelBinder-INFO:Action Convention Applied: Action Search on element Search.ViewModelBinder-INFO:Action Convention Applied: Action NextPage on element NextPage.ViewModelBinder-INFO:Action Convention Applied: Action PrevPage on element PrevPage.
ViewModelBinder-INFO:Binding Convention Applied: Element Tags.
ActionMessage-INFO:Action: Search availability update.ActionMessage-INFO:Action: Search availability update.ActionMessage-INFO:Action: PrevPage availability update.ActionMessage-INFO:Action: PrevPage availability update.ActionMessage-INFO:Action: NextPage availability update.ActionMessage-INFO:Action: NextPage availability update.
As we can see inside the log, the framework found some methods in our ViewModel called as the x:Name on the UIelement, so it automatically wired it. Even the command availability is automatically wired to property called Can+action name. Similar sort was reserved to the TextBox, automatically bound to the property Tags.
Let’s have a look now on how the command are actually implemented. Here the search function:
public IEnumerable<IResult> Search()
currentPage = 1;
public IEnumerable<IResult> PageSearch()
yield return new Wait(true);
yield return new Search(Tags, currentPage);
yield return new Wait(false);
NotifyOfPropertyChange(() => this.CanNextPage);
NotifyOfPropertyChange(() => this.CanPrevPage);
That’s could sound a little strange. The routine is returning an IEnumebrable<IResult>, what is this ? Well this is a strategy to make easy and readable code when we need to spawn asynchronous process, wait for the result, then go on with something else, and so on. This can result in a lot of messy code and complicated lambdas. By returning ( or better, Yielding ) an IResult we return an object that is capable to do something and signal when done. As a consequence, functions cooperate together and all returns in the “master” function, that is called CoRoutine. Not really a new idea since comes from Knuth, but in fact C# has not a native way of express such a context. Result are obtained in C# by an orchestration part ( implemented in Caliburn ) and leveraging the yield statement to leave and re-enter the main routine. I think it is interesting to know that someone creates the same strategy before the yield statement were created ( NET 2.0 ), have a look here if you are courious. It is important to know that implementing the acgtions as CoRoutines is not mandatory, but is strongly encouraged when you have to deal with sync-async calls wired together.
Before ending, let’s have a look on how we wire an IoC to that strategy. This is done by customizing the bootstrapper, here an example:
protected override object GetInstance(Type service, string key)
Caliburn call the function above when he need to instantiate an object, or when we try to instantiate something using the IoC static class. So that function is the extension point to bind the container. In the simple application I bound NInject, but any container can probably fit the purpose. Note that, even if you use the static IoC, without customizing the bootstrapper, natively Caliburn does not perform any IoC, but just plainly creates the requested type.
So the application is finished:
And we manage to avoid writing any code inside the view. And it is not all, Caliburn Micro has a lot of feature for us, even remaining a thin framework.
a@href@title, b, strike, strong
The opinions expressed herein are my own personal opinions and do not represent
my employer's view in any way.