MAUI how to access the view model inside a command where x:DataType is set

1 day ago 3
ARTICLE AD BOX
<CollectionView.ItemTemplate> <DataTemplate x:DataType="models:ParcelDTO"> <SwipeView> <SwipeView.RightItems> <SwipeItems Mode="Execute"> <SwipeItem BackgroundColor="Red" Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:BarcodeScannerViewModel}}, Path=DeleteParcelCommand}" CommandParameter="{Binding .}" Text="Delete" /> </SwipeItems> </SwipeView.RightItems> <Frame Margin="5,2" Padding="10" BackgroundColor="#F2F2F2" CornerRadius="10" HasShadow="False"> <Label HorizontalOptions="Center" Text="{Binding Barcode}" TextColor="Black" /> </Frame> </SwipeView> </DataTemplate> </CollectionView.ItemTemplate>

What is the correct command to access the view model DeleteParcel command?

marc_s's user avatar

marc_s

760k186 gold badges1.4k silver badges1.5k bronze badges

fARcRY's user avatar

4

This question is similar to: Access parent DataContext from DataTemplate. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.

2026-02-08 17:00:46 +00:00

Commented 13 hours ago

This has nothing to do with the x:DataType being set. You simply want to access a parent DataContext from a DataTemplate, see the other question. And as you can see there, AncestorType={x:Type viewmodel:BarcodeScannerViewModel}} won't work, because you have to specify a View type, not a ViewModel one. The ViewModel type never shows up in the visual tree, but the View that's bound to it might.

2026-02-08 17:30:12 +00:00

Commented 13 hours ago

@null you should not link WPF questions, even less mark them as duplicates. It is pretty standard for MAUI to have your VM used as DataType for the XAML, and then bind a collection view item source to a list, and specify the data type of the data template. The documentation: learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/…. Pretty much we do this in MAUI on every page.

2026-02-09 06:11:06 +00:00

Commented 49 mins ago

Can you check if you have "BarcodeScannerViewModel" set as BindingContext for your page, and then check if you have [RelayCommand] DeleteParcel (check for spelling, and maybe test it on a button outside the collection view). Last you should put a breakpoint and see if it is not called.

2026-02-09 06:17:25 +00:00

Commented 42 mins ago

Read Entire Article