donghua
donghua

Reputation: 3

how to dynamically determine the view model using Catel Mvvm

Catel MVVM framework is a very good mvvm framework, It automaticaly maps views to viewmodels, saving a lot time of my daily work. Now I encountered a problem, I want to map one view to a few of veiw models during runtime, i searched catel offical document, and found it said:

" Determining the view model dynamically when using the UserControl is extremely easy. You can override the GetViewModelType(object) method like this:

protected override Type GetViewModelType(object dataContext)
{
    if (dataContext is Rectangle)
    {
        return typeof (RectangleViewModel);
    }

    if (dataContext is Circle)
    {
        return typeof (CircleViewModel);
    }

    return null;
}

"

but dont't know where to override above GetViewModelType, I even did not find this method in Catel source codes.

Upvotes: 0

Views: 643

Answers (1)

Geert van Horrik
Geert van Horrik

Reputation: 5724

The GetViewModelType is obsolete. If you found it in the docs, please let me know where, then I will remove it (or feel free to remote it yourself, it's all editable for everyone).

You can register a custom view model mapping like this in the startup of your app:

var dependencyResolver = this.GetDependencyResolver();
var viewModelLocator = dependencyResolver.Resolve<IViewModelLocator>();

viewModelLocator.RegisterView<MyDrawingView, RectangleViewModel>();

If you want it more dynamic, you can implement your own IViewModelFactory where you can return the right view model based on the model being passed in.

Upvotes: 1

Related Questions