I have a small MAUI program using CollectionView
- and per item, there are buttons attached with a command (like changeitem)
The app is working. But I am getting warnings at compile and runtime about data binding.
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:CheckItem">
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="{StaticResource StdSpacing}">
<Grid
Grid.Column="1"
Margin="{StaticResource StdMargin}"
ColumnDefinitions="auto,auto"
ColumnSpacing="{StaticResource StdSpacing}">
<Button
Grid.Column="0"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:OverviewViewModel}}, Path=ChangeItemCommand}"
CommandParameter="{Binding .}"
Style="{x:StaticResource GoogleFont}"
Text="{x:Static font:GoogleIconFont.Edit}" />
</Grid>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
The commands are located in the ViewModel viewmodel:OverviewViewModel
whereas the data model for an item is located in model:CheckItem
.
The ContenPage starts with
x:Class="BicycleCheckList.OverviewPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:font="clr-namespace:BicycleCheckList.Utils"
xmlns:local="clr-namespace:BicycleCheckList.Resources.Strings"
xmlns:model="clr-namespace:BicycleCheckList.Models"
xmlns:utils="clr-namespace:BicycleCheckList.Utils"
xmlns:viewmodel="clr-namespace:BicycleCheckList.ViewModels"
Title="{Binding Title}"
x:DataType="viewmodel:OverviewViewModel">
On Compile time, I am getting a warning:
XC0045 Binding: Property "ChangeItemCommand" not found on "BicycleCheckList.Models.CheckItem".
The binding of the command Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:OverviewViewModel}}, Path=ChangeItemCommand}"
does not find the command.
Why?
The (toy) app is also available on Github
While it looks somewhat redundant, you can specify the x:DataType
of the binding. I believe all you need to do is change your Button
declaration to:
<Button
Grid.Column="0"
Command="{Binding x:DataType=viewmodel:OverviewViewModel, Source={RelativeSource AncestorType={x:Type viewmodel:OverviewViewModel}}, Path=ChangeItemCommand}"
CommandParameter="{Binding .}"
Style="{x:StaticResource GoogleFont}"
Text="{x:Static font:GoogleIconFont.Edit}" />
(I would normally put x:DataType
at the end, but then it wouldn't be visible without scrolling...)