Search code examples
c++xamltemplateswindows-runtimewinui-3

WinUI 3 - C++/WinRT DataTemplateSelector : Unable to cast object


I want to create a Template Selector in WinUI 3 using c++/WinRT.

For example, if the type of a person is "Employee" i want to show his name in Red and if is "Unemployee", in Blue.

I recreate the example from Microsoft but i got this error

The code is here . All VisualStudio components are up to date.

XAML code:

<StackPanel>

    <Page>
        <Page.Resources>

            <DataTemplate x:Key="template1" x:DataType="x:Int32">
                <Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="{ThemeResource  SystemChromeLowColor}">
                    <TextBlock Text="{x:Bind}" />
                </Button>
            </DataTemplate>

            <DataTemplate x:Key="template2" x:DataType="x:Int32">
                <Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="{ThemeResource SystemAccentColor}">
                    <TextBlock Text="{x:Bind}" />
                </Button>
            </DataTemplate>

            <local:Selector x:Key="mySelector"
                firstTemplate="{StaticResource template1}"
                secondTemplate="{StaticResource template2}"/>

        </Page.Resources>
    </Page>

    <ListView
          ItemTemplateSelector = "{StaticResource mySelector}">
    </ListView>

</StackPanel>

Thanks!


Solution

  • I came across your problem and the answer to it was mixing up the Windows and Microsoft namespaces into the data template selector implementation. Try to use just one namespace like the Microsoft namespace.

    I made a github repo with the minimum code for the data template selector example here