A C# source generator that automatically implements static view locator for Avalonia without using reflection.
Add NuGet package reference to project.
<PackageReference Include="StaticViewLocator" Version="0.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>Annotate view locator class with [StaticViewLocator] attribute, make class partial and imlement Build using s_views dictionary to retrieve views for data objects.
[StaticViewLocator]
public partial class ViewLocator : IDataTemplate
{
public Control? Build(object? data)
{
if (data is null)
{
return null;
}
var type = data.GetType();
if (s_views.TryGetValue(type, out var func))
{
return func.Invoke();
}
throw new Exception($"Unable to create view for type: {type}");
}
public bool Match(object? data)
{
return data is ViewModelBase;
}
}Source generator will generate the s_views dictionary similar to below code using convention based on ViewModel suffix for view models subsituted to View suffix.
public partial class ViewLocator
{
private static Dictionary<Type, Func<Control>> s_views = new()
{
[typeof(StaticViewLocatorDemo.ViewModels.MainWindowViewModel)] = () => new TextBlock() { Text = "Not Found: StaticViewLocatorDemo.Views.MainWindowView" },
[typeof(StaticViewLocatorDemo.ViewModels.TestViewModel)] = () => new StaticViewLocatorDemo.Views.TestView(),
};
}StaticViewLocator is licensed under the MIT license. See LICENSE file for details.