Contextual resolution of viewmodels

19 views
Skip to first unread message

Ross

unread,
Mar 31, 2011, 6:17:40 AM3/31/11
to nRoute
Hi Rishi,

We have a requirement were we would need to resolve different view
models for the same URL based on the type of user logged in. i.e. we
need to display some information differently for clients and agents.

Is there a best practice way of doing this with nRoute?

Thanks

Rishi Oberoi

unread,
Apr 11, 2011, 7:58:53 AM4/11/11
to nro...@googlegroups.com
Hi Ross, sorry for the delay in replying. Now, below is an example of how I've done something similar in one of my projects:
[MapNavigationContent("Pickers/Entity/{EntityType}/")]
public partial class EntityPickerView : UserControlISupportNavigationLifecycle
{
    private const string ENTITY_TYPE_KEY = "EntityType";
    private const string KNOWN_ENTITY_FORMAT = "Entities.Operations.{0}";
 
    private readonly static Type PICKER_VIEWMODEL_GENERIC_TYPE = typeof(EntityPickerViewModel<>);
 
    private ISupportNavigationLifecycle _viewModel;
 
    public EntityPickerView()
    {
        InitializeComponent();
    }
 
    public string Title
    {
        get { return _viewModel.Title; }
    }
 
    public void Initialize(ParametersCollection requestParameters)
    {
        var _type = Type.GetType(Convert.ToString(requestParameters[ENTITY_TYPE_KEY]), false);
        if (_type == null) _type = Type.GetType(string.Format(KNOWN_ENTITY_FORMAT, requestParameters[ENTITY_TYPE_KEY]), true);
        this.DataContext = ResourceLocator.GetResource(PICKER_VIEWMODEL_GENERIC_TYPE.MakeGenericType(_type));
 
        _viewModel = this.DataContext as ISupportNavigationLifecycle;
        if (_viewModel != null) _viewModel.Initialize(requestParameters);
    }
 
    public void Closing(Action<bool> confirmCallback)
    {
        if (_viewModel != null) _viewModel.Closing(confirmCallback);
    }
}
Basically, I take in a EntityToken that tells me the type to resolve. Now, this might be too specific, you can obviously make this more generic and/or create a behavior that can encapsulate this technique. 

Also FYI, there is also a lower level/infrastructural way to do something similar - look into something called the IViewModelProvider. A VM provider is used to resolve the ViewModel, and a custom implementation can encapsulate any kind of domain logic to resolve the VM. 

Hope this helps,
Rishi

Ross

unread,
Apr 14, 2011, 5:50:35 AM4/14/11
to nRoute
Thanks Rishi, will see what we can do.
Reply all
Reply to author
Forward
0 new messages