# Sunday, July 24, 2011

I’ve been using the MvvmLight Toolkit on a project now for several weeks. At first, the ViewModelLocator pattern the toolkit uses didn’t bother me. But after you wonder why your view can’t be located and then debug everything only to discover that you forgot to create the ViewModel in the ViewModelLocator.

I first thought about switching the ViewModelLocator to inherit from DynamicObject and using MEF to discover the VIewModel’s. A quick search lead me to discover that I’m not the only one to have that same thought Smile

The one thing I didn’t like about using Dynamic and MEF for discovering the ViewModel was the design time experience took a big hit. Locating the ViewModel was now much more expensive at design time.

I started started doing more thinking, and wondered if I could use T4 to generate the ViewModelLocator for me. After more thought, I knew I had to be able to use T4 to generate the ViewModelLocator, heck T4MVC uses it to generate a bunch of helper classes.

Because I’m big on using IoC in my apps, I’ve also added the ability to get the ViewModel from an IoC container if the application isn’t in design mode.

There are two files that are required to make this approach work. ViewModelLocator.tt, and ViewModelLocator.settings.t4. The settings file exists so you can configure the what’s and how’s. If you use the default setup for MvvmLight, the only thing you will have to change is the IoC stuff.

To use the T4 ViewModelLocator, delete your existing ViewModelLocator.cs class in your ViewModel folder, and drop the two T4 files into your ViewModel folder. Once that happens, you will see a new icon show up in the solution explorer called “Transform All Templates.” Click that icon to have your ViewModelLocator automatically generated for you, compile and run Smile


Download the T4 templates!

Next time, I’ll write a post about using MEF, DynamicObject and other code to dynamically locator your ViewModels to create a composable application (Wait, didn’t I just say there were performance issues? Yes, but sometimes you have to take the hit).

Please post your thoughts on all this, I would be really interested in hearing other perspectives!

.NET | MVVM | MvvmLight | WPF
All comments require the approval of the site owner before being displayed.
(will show your gravatar icon)
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview