Composition View Locator
Overview
CompositionViewLocator is a component that automatically finds and binds a View to its corresponding ViewModel (presentation logic). It implements the IDataTemplate interface for Avalonia UI and uses the MEF to dynamically resolve views from the dependency container.
How It Works
CompositionViewLocator uses a matching algorithm to find the correct view for a given view model:
Direct Type Match — searches for a view by the ViewModel's full type name
Interface Match — if no direct match is found, searches for views based on the interfaces implemented by the ViewModel
Base Class Hierarchy — if still not found, searches through the base class hierarchy
Fallback — if no view is found, displays a
TextBlockwith the ViewModel's type name for debugging
The locator only matches the objects implementing IViewModel:
Setup
To use CompositionViewLocator, add it to your application's data templates in the app initialization App.axaml.cs file:
ExportViewFor Attribute
Use the [ExportViewFor] attribute to register a view for a view model in the composition container.
Generic version:
Non-generic version:
Example
Basic View Registration
Troubleshooting
View Not Found
If a view cannot be found, a TextBlock with the view model's type name will be displayed. This helps identify missing view registrations during development.
Make sure to:
Decorate your view class with
[ExportViewFor<...>]or[ExportViewFor(typeof(...))]Verify the composition container is properly initialized