Thursday, May 10, 2012

Using Custom ViewModelLocators in MvvmCross


In MvvmCross, the "container" for ViewModelLocators is the MvxApplication object. By default it uses a convention based MvxDefaultViewModelLocator which just tries to construct ViewModel instances by using their declared constructors which have string parameters.
If you would like to use your own ViewModel locator, then the easiest way is simple to inherit from MvxViewModelLocator and to provide either public Properties or public Methods which return your ViewModel instances:
e.g:
public class MyViewModelLocator : MvxViewModelLocator
{
    public MyFirstViewModel CreateFirst()
    {
        return new MyFirstViewModel();
    }

    public MySecondViewModel CreateSecond(string aParameter)
    {
        var someLookup1 = ComplicatedStaticThing1.Lookup(aParameter);
        var viewModel = new MySecondViewModel(someLookup1);

        var someLookup2 = ComplicatedStaticThing2.Lookup(aParameter, someLookup1);
        viewModel.DoSomething(someLookup2);

        return viewModel;
    }

    private readonly MyThirdViewModel _third = new MyThirdViewModel();
    public MyThirdViewModel Third
    {
        get
        {
            return _third;
        }
    }
}
If you want to go even lower than this, then you can also implement IMvxViewModelLocator directly instead.
To add the ViewModelLocator to the application, simply instantiate and add it inside your app - e.g:
public class App 
    : MvxApplication
    , IMvxServiceProducer
{
    public App()
    {
        this.RegisterServiceInstance(new StartApplicationObject());

        base.AddLocator(new MyViewModelLocator());

        // to disable the default ViewModelLocator, use:
        // base.UseDefaultViewModelLocator = false;
    }
}

Note: - apart from for design time data, I now very rarely find the need to implement custom ViewModelLocator - in general everything I want to do can be done within the ViewModel construction.

No comments:

Post a Comment