ViewLocator

The IViewLocator class is responsible for resolving the right views for a view model. Before Catel 3.0, the IUIVisualizerService was responsible for resolving the view, but this responsibility is now taken over by the IViewLocator. The UIVisualizerService internally uses the IViewLocator to resolve the views. 

Resolving by naming convention

It is possible to resolve views using the IViewLocator. Then you can use the ResolveView method to resolve the view based on the type of the view model.

For example, the following view model:

Catel.Examples.ViewModels.MyViewModel

will be resolved as:

Catel.Examples.Views.MyView

Manually resolving a view using naming convention

To manually resolve a view using naming convention, use the following code:

var viewLocator = ServiceLocator.Default.ResolveType<IViewLocator>();
var viewType = viewLocator.ResolveView(typeof(MyViewModel));

Customizing naming conventions

By default, the IViewLocator uses the following naming conventions to resolve views:

For more information about naming conventions, see Naming conventions

However, it is possible to add or remove new naming conventions to support your own naming convention. For example, to add a new naming convention for a different assembly, use this code:

var viewLocator = ServiceLocator.Default.ResolveType<IViewLocator>();
viewLocator.NamingConventions.Add("MyCustomAssembly.Views.[VM]View");

Registering custom views

Sometimes, a class doesn’t follow a naming convention (for whatever reason possible). In such a case, it is possible to register a mapping manually using the following code:

var viewLocator = ServiceLocator.Default.ResolveType<IViewLocator>();
viewLocator.Register(typeof(MyViewModelNotFollowingNamingConvention), typeof(MyView));

Using a custom ViewLocator

If you want to have total freedom to determine which view is provided per view model (maybe there are other services that have an impact on this), it is possible to create a custom IViewLocator implementation. Then the only thing to do is to register it using the following code:

ServiceLocator.Default.RegisterType<IViewLocator, MyViewLocator>();

Contributions

We would like to thank the following contributors:

Want to contribute to the documentation? We have a guide for that!


Questions

Have a question about Catel? Use StackOverflow with the Catel tag!