onid jade
onid jade

Reputation: 23

How to have multiple datatemplates in UWP ListView (x:bind)

I'm stuck with my UWP app, I'm trying to follow MVVM principle with {x:bind} instead of the older WPF way {binding name}

But I'm stuck with my idea/development, I'm trying insert multiple DataTemplates within ListView (or GridView).

I want to do something like this as an example:

            <ListView.ItemTemplate>
                <DataTemplate x:DataType="localModels:Cars">
                    <StackPanel Orientation="Vertical">
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="Name:" />
                            <TextBox Text="{x:Bind Name}" />
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
                <!-- Here is the second DataTemplate which isn't allowed in UWP -->
               <DataTemplate x:DataType="localModels:Bikes">
                    <StackPanel Orientation="Vertical">
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="Name:" />
                            <TextBox Text="{x:Bind Name}" />
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>

As you can see, I have 2 DataTemplate: Cars and Bikes inside ListView.ItemTemplate.

Not sure if this is relevant: Cars.cs is inheriting from Bike.cs parent.

I don't really get why UWP doesn't accept more than 1 DataTemplate within ListView.ItemTemplate. Because I really want my ListView to show as many kind of data as possible.

What's the way to solve this issue in UWP and {x:bind}?

Upvotes: 2

Views: 1524

Answers (1)

P&#233;ter Csajtai
P&#233;ter Csajtai

Reputation: 898

You can use a DataTemplateSelector to determine which datatemplate should be selected based on your data type. Here you can find an example.

Upvotes: 4

Related Questions