- Obtain and Build the Code
- Setting Up a Project
When using the View.Model attached property, Caliburn uses the IViewStrategy to locate an appropriate view for the provided model. You can also use this service to locate Views manually.
The DefaultViewStrategy accomplishes its task by using a series of namespace conventions. For example, if your model is: My.Namespace.ViewModels.MyViewModel, then Caliburn will look for the following combinations: My.Namespace.Views.IMyView and My.Namespace.Views.MyView. It looks for patterns based on the following terms: "Presenter", "Model", "ViewModel" and "PresentationModel." and replaces them with "View." Once it finds a matching type, it will ask the IServiceLocator if it has an instance of the type. If one is not found, and the type is not abstract, the DefaultViewStrategy will attempt an Activator.CreateInstance. If no type is found or the Activator fails, the strategy will continue looking for pattern matches. If none are found, an exception will be thrown.Note:
the DefaultViewStrategy only searches assemblies registered with the IAssemblySource.
In addition to the built-in conventions, you can teach the DefaultViewStrategy about other patterns. For example, you can use the AddNamespaceAlias to map a model namespace to a view namespace. Alternatively, you can apply the ViewAttribute to a model in order to explicitly provide a view.
Caliburn's DefaultViewStrategy also understands the notion of Context. Therefor, it is capable of selecting different views for the same model based on the context in which the model is being displayed. Contextual information can be provided through the View.Context attached property. Contextual views can be specified by using the ViewAttribute. Caliburn also understands a namespace convention for contexts. So, if your model is: My.Namespace.ViewModels.MyViewModel and you specify a context of "Edit," the DefaultViewStrategy will search for My.Namespace.Views.MyViews.IEdit and My.Namespace.Views.MyViews.Edit.Note:
The DefaultViewStrategy will always check for My.Namespace.Views.MyViews.IDefault and My.Namespace.Views.MyViews.Default if no context is provided.
As always, you can replace the DefaultViewStrategy entirely by implementing IViewStrategy and registering your implementation with the framework. However, there are other ways to customize which may be simpler for your purposes. For example, you could inherit from DefaultviewStrategy and override GetTypeNamesToCheck. Doing so allows you to examine a model object and return a list of possible view names to search for based on your own conventions. You could also implement your own ViewAttribute by inheriting from ViewStrategyAttribute.