Using Structuremap to resolve ViewModels

One of the things I find myself doing over and over again when working in xaml-based applications is to create a ViewModelFactory based on Jeremy D. Miller’s StructureMap.

All my ViewModel classes are based on a class BaseViewModel:

    public class BaseViewModel : INotifyPropertyChanged

The fun, of course, begins when your viewmodels need to know about other viewmodels. Lets say, for instance that your main view contains a Container control in which you would like to swap views in. Using structuremap, it is easy to inherit the Registry class in order to stitch together associations between views and models:

public class ViewModelsRegistry : Registry
{
    public ViewModelsRegistry()
    {
        Rig<MainWindowView, MainVindowViewModel>(Registered.MainWindow);
        Rig<TrioEventsView, TrioEventsViewModel>(Registered.TrioEvents);
        Rig<NewsContentView, NewsContentViewModel>(Registered.NewsContent);
    }

    private void Rig<TControl, TViewModel>(Registered name) 
        where  TControl : ContentControl where TViewModel : BaseViewModel
    {
        For<ContentControl>().Singleton().Use<TControl>().Named(name.ToString());
        For<BaseViewModel>().Singleton().Use<TViewModel>().Named(name.ToString());
    }
}
 

The Registered reference is an enum that I use to keep tabs on what views/viewmodels that are implemented:

    public enum Registered
   
{
        Unknown = 0,
        MainWindow,
        TrioEvents,
        NewsContent,
        Locations
    }

As you can tell, the ViewModelsRegistry uses ContentControl as it’s container type. This makes it  compatible with all derivates, including Window and UserControl.
Following the factory pattern, the result follows:

public static class ViewModelFactory
{
    public static void Initialize(Registry registry)
    {
        ObjectFactory.Configure(o => o.AddRegistry(registry));            
    }

    public static ContentControl Get(Registered name)
    {
        var control = ObjectFactory.GetNamedInstance<ContentControl>(name.ToString());
        control.Loaded += (s, e) => {
            control.DataContext = GetDataContextFor(name);
        };
        return control;
    }

    public static BaseViewModel GetDataContextFor(Registered name)
    {
        return ObjectFactory.GetNamedInstance<BaseViewModel>(name.ToString());
    }
}
 

The ViewModelFactory basically leans on structuremap providing the method Get() that stitches together a view and it’s model. One example of such use:

 

        public void LoadEvents(object dummy)
        {
            SetViewModel(Registered.TrioEvents);
        }

        private void SetViewModel(Registered name)
        {
            if(!_loadedControls.ContainsKey(name))
                _loadedControls.Add(name, ViewModelFactory.Get(name));
                
            CurrentContent = _loadedControls[name];
        }

In the above snippet, taken from the MainWindowViewModel,  LoadEvents is bound to a button click on the Main Window. Once clicked, If I haven’t already loaded the control, I use the factory.Get() method to create a UserControl with initalized datacontext, before I finally set the ContentPresenter (CurrentContent) on the Main window viewmodel.

The factory can easilly be expanded to swap out datacontexts, provide different views. This blog post is mainly about using structuremap to make it happen.

Jeg bare tøyser

 

About digitaldias

Software Engineer at Microsoft during the day, photographer, videographer and gamer in the evening. Also a father of 3. Pedro has a strong passion for technology, and gladly shares his findings with enthusiasm.

View all posts by digitaldias →

2 Comments on “Using Structuremap to resolve ViewModels”

  1. Howdy

    I just checked out your website digitaldias.com and wanted to find out if you need help for SEO Link Building ?

    If you aren’t using SEO Software then you will know the amount of work load involved in creating accounts, confirming emails and submitting your contents to thousands of websites.

    With THIS SOFTWARE the link submission process will be the easiest task and completely automated, you will be able to build unlimited number of links and increase traffic to your websites which will lead to a higher number of customers and much more sales for you.

    IF YOU ARE INTERESTED, We offer you 7 days free trial
    CONTACT US HERE ==> dindinaa421@gmail.com

    Regards,
    Best Seo Software

  2. Howdy

    I Will Provide 20.000 Backlinks From Blog Comments for digitaldias.com,
    By post 400k blog comments from where you will receive at least 20.000 live links.

    – Use unlimited URLs
    – Use unlimited keywords (anchor text)
    – All languages supported
    – Link report included

    Boost your Google ranking, get more traffic and more sales!

    IF YOU ARE INTERESTED
    CONTACT US => lisaf2zw526@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *