maui

Can't pass bound view model as command parameter


<CollectionView.ItemTemplate>
                <DataTemplate x:DataType="data:PhotoItemViewModel">
                    <Border StrokeThickness="1"
                            Padding="0">
                        <VerticalStackLayout>
                            <Grid>
                                <Image
                                    Source="{Binding ThumbnailImageSource}"
                                    Aspect="AspectFill"
                                    HeightRequest="120"
                                    WidthRequest="120">
                                    <Image.Behaviors>
                                        <toolkit:TouchBehavior
                                            
                                            LongPressCommand="{Binding x:DataType=ContentPage, Source={x:Reference Page}, Path=BindingContext.LongPressCommand}"
                                            LongPressCommandParameter="{Binding .}"/>
                                    </Image.Behaviors>
                                </Image>
                                
                                <CheckBox
                                    IsChecked="{Binding IsSelected}"
                                    IsVisible="{Binding x:DataType=ContentPage,Source={x:Reference Page}, Path=BindingContext.IsSelectionMode}"
                                    VerticalOptions="Start"
                                    HorizontalOptions="End"
                                    Margin="5"
                                    BackgroundColor="White"
                                    Opacity="0.8"/>
                            </Grid>
                        </VerticalStackLayout>
                    </Border>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

Here I'm using a collection view to display a list of images, with the support of long press gesture on each image, implemented using CommunityToolkit.Maui's TouchBehavior. And my view model's LongPressCommand command is initialized with this method:

  private void OnPhotoLongPressed(PhotoItemViewModel photo)
    {
        IsSelectionMode = true;
        // photo.IsSelected = true;
    }

Now the issue is the photo passed from the command is always null.


Solution

  • Turns out there're just couple of things to add in order to have my original code to work:

    1. Add BindingContext assignment to the behavior;

    2. Set x:DataType to the BindingContext;

    3. Use x:Reference to refer to the parent Image control and set its BindingContext to the behavior.

    Hope this could be added to the documentation as this is quite a common scenario.