Tuesday, October 7, 2014

design data in wpf (best practise)

I used to have a DB connection in my wpf applications which will be set from outside so that the application has no idea what the connection string could be. The result is, that I start my application development without any design data.

What is nice here is that you can check whether you are in design mode or not and set the connection string. Therefore check:


... but in fact, I really don't like that solution because it works only if you have wpf references in the project what a DB-access layer typically doesn't have. Pushing the connection string from the ui-layer to the business logic layer and then to the dbaccess-layer for design makes it a mess (spaghetti code). Moreover you need a database connection even at design time to work on the ui, what can be painful too.

I found my solution inside the following msdn blog post with some additional brain work:


I would recommend in a MVVM pattern UI to set the datacontext to the VM and set d:DesignData right afterwards to a child class of that class.

so e.g.: a grid's data context is bound to a class called something like MainWindowViewModel and d:DataContext (as described at the msdn article) is bound to something like MainWindowViewModelDesignData.

The ...DesignData should inherit from the base view model and initialize the properties with hard coded design data values (or maybe xml files which are always available on hard drive). I would recommend to set extreme values (min/max values) inside the view model or even better prepare more than one vm-designdata class (or what I would do: put in a switch which can be modified quickly), because it is much easier to change the desing data, compile, close and open the window than to compile, start, prepare test data, check, prepare other test data, check,... and so on. The design data is giving you a perfect overview how the ui would look like and is a perfect solution to test your ui about extreme values entered by the user (e.g.: a login name can have 7 to 50 characters: make cases with a) only 7 char logins, b) only 50 char logins and c) a mix with even 25 char logins).

This worked fine for me. Please let me know if you see it differently.

kr, daniel


today (about a month later) I used the mvvm light framework which is shipped with a dependency injection service, where view-models are registered. With mvvm light it is even easier to register design data in design mode.

Service-Locator code:

            if (ViewModelBase.IsInDesignModeStatic)
                SimpleIoc.Default.Register<MainViewModel, MainDesignViewModel>();

kind regards, Daniel

No comments: