Creating "lookless" views in MVVM
We would like to create an application that can be quickly and easily "re-skinned" with as much flexibility as possible. Usually this is achieved through swapping out templates and styles in a resource dictionary.
Custom controls in WPF are designed to be "lookless." All of the logic goes in code, control templates in dictionaries are used to associate a look with the control.
There is a lot of overlap between MVVM and custom controls. A lot of developers say that MVVM trumps custom controls. Both can be viewed as methods of moving logic out of the view and into another code file. I think there can be semantic difference between the two if a VM contains do开发者_如何学运维main related logic while custom controls contain view-specific logic.
What is the best method for moving the relevant view XAML into a resource dictionary that can be swapped out? Should I use straight data templates in a dictionary (not my preferred method because the views are complex)? Should I create a custom control to replace the view and define a control template for it (results in duplicate code between the control and the VM)? Should I use UserControls for the views and isolate the XAML for these controls so that these files can be swapped out with the resource dictionaries?
How would you handle this problem? Any suggestions?
Thanks!
Personally I like using an using an IValueConverter
like this post.
This basically requires you to:
- Put one entry in your application resources to require WPF use the value converter
- Implement the
IValueConverter
with the custom logic you want.
This allows you as much flexibility as you deem necessary for your application. The post above uses a convention over configuration look up strategy, but you can easily swap that out for a converter that relies on a service that you can register/resolve objects like so:
public static class ServiceProvider
{
public void Register<TView>(Type ViewModelType);
public void Register(IDictionary<Type,Type> ViewLookup);
public object Resolve(object ViewModel);
}
HTH
精彩评论