WinUI 3 DataTemplateSelector always crashed when using AOT
See the question and my original answer on StackOverflowYour project doesn't even work w/o AOT publishing, it raises an InvalidCastException
error:
The problem comes from the fact you want to expose a "pure" managed object (of type ADataTemplateSelector
) to the underlying WinUI3 (native) layers but there's not enough information for C#/WinRT to project this type back. Invalid cast here means: this type doesn't implement what's needed to participate to the XAML/WinUI3 party.
If you work with Visual Studio and take a closer look over this managed class, you will see this:
Class ... implements WinRT interface but it ... isn't marked partial.
The warning tells you to add a partial
keyword to the class to allow C#/WinRT to generate necessary information for this type to be recognised as a valid WinUI3 framework type:
public partial class ADataTemplateSelector : DataTemplateSelector
{
...
}
Once you've done that the warning should go and the project should run and work when published as AOT.
PS: there are other warnings in this code. In general and especially with AOT publishing you really want to make sure there are none left, even when it seems to work: