Hello,
How to set x:DataType in a DataTemplate to a Tuple in XAML?
Tuple<int, string, Person>
is not a named type in XAML, you cannot set x:DataType="{x:Type sys:Tuple(``1, ``2, ``3)}"
.
If you want to use Compiled Bindings, please use strong typing, create a wrapper class instead of using Tuple
like following code.
public class PersonRecord
{
public int Id { get; set; }
public string Message { get; set; }
public Person Person { get; set; }
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Here is my edited viewmodel use strong typing.
public class MainViewModel
{
public ObservableCollection<PersonRecord> Items { get; } =
new ObservableCollection<PersonRecord>
{
new PersonRecord { Id = 1, Message = "Hello", Person = new Person { Name = "Alice", Age = 30 } },
new PersonRecord { Id = 2, Message = "World", Person = new Person { Name = "Bob", Age = 25 } }
};
//public ObservableCollection<Tuple<int, string, Person>> Items { get; } =
// new ObservableCollection<Tuple<int, string, Person>>
// {
// new Tuple<int, string, Person>(1, "Hello", new Person { Name = "Alice", Age = 30 }),
// new Tuple<int, string, Person>(2, "World", new Person { Name = "Bob", Age = 25 })
// };
}
After that, I can use x:DataType
in the xaml without XC0022 warning.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiApp5"
x:DataType="local:MainViewModel"
x:Class="MauiApp5.MainPage">
<ContentPage.BindingContext>
<local:MainViewModel/>
</ContentPage.BindingContext>
<CollectionView ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="local:PersonRecord">
<HorizontalStackLayout>
<Label Text="{Binding Id}"/>
<Label Text="{Binding Message}"/>
<Label Text="{Binding Person.Name}"/>
<Label Text="{Binding Person.Age}"/>
</HorizontalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage>
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.