WPF MVVM: Convention over Configuration for ResourceDictionary ?

Posted by Jeffrey Knight on Stack Overflow See other posts from Stack Overflow or by Jeffrey Knight
Published on 2009-04-20T13:40:26Z Indexed on 2010/03/12 15:17 UTC
Read the original article Hit count: 400

Filed under:
|


Update

In the wiki spirit of StackOverflow, here's an update:

I spiked Joe White's IValueConverter suggestion below. It works like a charm.

I've written a "quickstart" example of this that automates the mapping of ViewModels->Views using some cheap string replacement. If no View is found to represent the ViewModel, it defaults to an "Under Construction" page. I'm dubbing this approach "WPF MVVM White" since it was Joe White's idea. Here are a couple screenshots.

The first image is a case of "[SomeControlName]ViewModel" has a corresponding "[SomeControlName]View", based on pure naming convention. The second is a case where the ModelView doesn't have any views to represent it. No more ResourceDictionaries with long ViewModel to View mappings. It's pure naming convention now.

Wpf Mvvm White

I'm hosting a download of the project here: http://rootsilver.com/files/Mvvm.White.Quickstart.zip

I'll follow up with a longer blog post walk through.


Original Post

I read Josh Smith's fantastic MSDN article on WPF MVVM over the weekend. It's destined to be a cult classic.

It took me a while to wrap my head around the magic of asking WPF to render the ViewModel.

It's like saying "Here's a class, WPF. Go figure out which UI to use to present it."

For those who missed this magic, WPF can do this by looking up the View for ModelView in the ResourceDictionary mapping and pulling out the corresponding View. (Scroll down to Figure 10 Supplying a View ).

The first thing that jumps out at me immediately is that there's already a strong naming convention of:

classNameView  ("View" suffix)
classNameViewModel ("ViewModel" suffix)

My question is:

Since the ResourceDictionary can be manipulated programatically, I"m wondering if anyone has managed to Regex.Replace the whole thing away, so the lookup is automatic, and any new View/ViewModels get resolved by virtue of their naming convention?

[Edit] What I'm imagining is a hook/interception into ResourceDictionary.

... Also considering a method at startup that uses interop to pull out *View$ and *ViewModel$ class names to build the DataTemplate dictionary in code:

//build list
foreach ....
    String.Format("<DataTemplate DataType=\"{x:Type vm:{0} }\"><v:{1} /></DataTemplate>", ...)

© Stack Overflow or respective owner

Related posts about wpf

Related posts about mvvm