Connect ViewModel and View using Unity

Posted by brainbox on Weblogs See other posts from Weblogs or by brainbox
Published on Sun, 14 Mar 2010 13:47:00 GMT Indexed on 2010/03/14 14:05 UTC
Read the original article Hit count: 396

In this post i want to describe the approach of connecting View and ViewModel which I'm using in my last project.

The main idea is to do it during resolve inside of unity container. It can be achived using InjectionFactory introduced in Unity 2.0

 public static class MVVMUnityExtensions
    public static void RegisterView<TView, TViewModel>(this IUnityContainer container) where TView : FrameworkElement
        container.RegisterView<TView, TView, TViewModel>();

    public static void RegisterView<TViewFrom, TViewTo, TViewModel>(this IUnityContainer container)
        where TViewTo : FrameworkElement, TViewFrom
        container.RegisterType<TViewFrom>(new InjectionFactory(
            c =>
                var model = c.Resolve<TViewModel>();
                var view = Activator.CreateInstance<TViewTo>();
                view.DataContext = model;
                return view;

And here is the sample how it could be used:

var unityContainer = new UnityContainer();

unityContainer.RegisterView<IFooView, FooView, FooViewModel>();

IFooView view = unityContainer.Resolve<IFooView>(); // view with injected viewmodel in its datacontext

Please tell me your prefered way to connect viewmodel and view.

© Weblogs or respective owner

Related posts about Silverlight

Related posts about wpf