Maui: [BUG] TouchBehavior crash

Is there an existing issue for this?

  • I have searched the existing issues

Did you read the “Reporting a bug” section on Contributing file?

Current Behavior

I have a CollectionView like this

<CollectionView
    IsVisible="{Binding isNotBusy}"
    ItemsSource="{Binding CoursesAssigned}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="model:Course">
            <Border
                Margin="50"
                Stroke="Purple"
                StrokeThickness="1">
                <Border.StrokeShape>
                    <RoundRectangle CornerRadius="8,8,8,8" />
                </Border.StrokeShape>
                <Border.Behaviors>
                    <mct:TouchBehavior Command="{Binding Path=GoToDetailsCommand, Source={x:RelativeSource AncestorType={x:Type vm:MyCoursesPageViewModel}}}"
                        CommandParameter="{Binding .}"
                        DefaultBackgroundColor="Transparent"
                        HoveredBackgroundColor="CornflowerBlue"
                        PressedBackgroundColor="CornflowerBlue" />
                </Border.Behaviors>`

But when I run it, I get the error

Operation is not valid due to the current state of the object.

Expected Behavior

My command is declared in my viewModel

 [RelayCommand]
 async Task GoToDetails(Course course) {

     await appService.NavigateTo($"{nameof(MyCoursesDetailPage)}",
         true, new Dictionary<string, object> {
         {"Course", course }
     });
 }

So I am expecting my command to go the MyCoursesDetailPage when I click the border

Steps To Reproduce

  1. Create a new Maui project
  2. Install the mct (Maui community toolkit)
  3. Create some sort of class to represent an object, like fruits.
  4. create a collectionView
  5. Create a border
  6. attach the Touch behavior to a border

Link to public reproduction project repository

https://github.com/eduardoagr/TouchBehaviorExample

Environment

- .NET MAUI CommunityToolkit:
- OS: Windows, Android
- .NET MAUI:

Anything else?

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 5
  • Comments: 55 (23 by maintainers)

Most upvoted comments

@eduardoagr & @r-work can you have a look at this post from @brminnick on SO. Here he shows exactly how to set the binding context on the behavior appropriately, I have seen the crashes when not setting it the recommended way too.

I’m currently in the process of updating the MCT samples & documentation to explicitly call this issue out and show the appropriate way to use the behavior, I have put this in my docs pr but the way you should setup the behavior to pass a command is here:

<ContentPage x:Name="Page">
    <HorizontalStackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="Center">
        <HorizontalStackLayout.Behaviors>
            <mct:TouchBehavior
                BindingContext="{Binding Source={x:Reference Page}, Path=BindingContext}"
                Command="{Binding IncreaseTouchCountCommand}"
                DefaultAnimationDuration="250"
                DefaultAnimationEasing="{x:Static Easing.CubicInOut}"
                PressedOpacity="0.6"
                PressedScale="0.8" />
        </HorizontalStackLayout.Behaviors>

        <ContentView
            BackgroundColor="Gold"
            HeightRequest="100"
            WidthRequest="10" />
        <Label
            LineBreakMode="TailTruncation"
            Text="The entire layout receives touches"
            VerticalOptions="Center" />
        <ContentView
            BackgroundColor="Gold"
            HeightRequest="100"
            WidthRequest="10" />
    </HorizontalStackLayout>
</ContentPage>

The checklist is:

  • Put an x:Name="Page on your root element (assuming ContentPage)
  • Set the BindingContext: BindingContext="{Binding Source={x:Reference Page}, Path=BindingContext}"
  • Reference the Command normally: Command="{Binding IncreaseTouchCountCommand}"

I’ve opened an issue with maui because I’m convinced the RelativeSource should be working… We will see that what say!

It work for me:

LongPressCommand="{Binding Source={x:Reference YourContentPageName}, Path=BindingContext.YourLongPressCommand}"

which MauiVersion are you using?

8.0.14, the x:Reference works for me, I’m talking about the relative binding Command="{Binding Source={RelativeSource AncestorType={x:Type vm:MyViewModel}}, Path=MyCommand}" not working.

This is definitely a regression from XCT since my Maui TouchEffect was able to use relative bindings, I noticed this issue when removing my port from my apps.

Binding issues will be fixed in the next release, see #1791 for details.

The TouchBehavior from this release will inherit the BindingContext of the VisualElement it is attached to (if it exists). This means it will behave in the same way the XCT effect did & the way my Maui.TouchEffect port did. I believe the change will be hotfixed so it should be available soon!

Why do we have to use a name for the page, I always reference the vm, and that is what I was trying to do

Are we sure RelativeSource’s in maui are working the way they are intended to? I feel like this behaviour should be a bug, if it isn’t a bug we need to support it properly because data templates do become very annoying to work with when using the MCT version!

So you are using this inside a DataTemplate? Yes I don’t think that will work right now

this is how you can fix this.

  1. Use the x:Name, for naming your XAML Page
  2. Create a relay command in your viewModel
  3. When binding the command, use BindingContext.YourCommand and as reference, use the name of the XAML

As a workaround, you could do something like

` <CollectionView Grid.Row="1" Grid.ColumnSpan="3" Margin="5" IsVisible="{Binding isNotBusy}" ItemsSource="{Binding CoursesAssigned}">

    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="model:Course">
            <Border StrokeThickness="2">
                <Border.StrokeShape>
                    <RoundRectangle CornerRadius="8" />
                </Border.StrokeShape>
                <Border.Behaviors>
                    <mct:TouchBehavior
                        DefaultBackgroundColor="Transparent"
                        HoveredBackgroundColor="CornflowerBlue"
                        PressedBackgroundColor="CornflowerBlue" />
                </Border.Behaviors>
                <Border.GestureRecognizers>
                    <TapGestureRecognizer
                        Command="{Binding Path=GoToDetailsCommand, Source={x:RelativeSource AncestorType={x:Type vm:MyCoursesPageViewModel}}}"
                        CommandParameter="{Binding .}" />
                </Border.GestureRecognizers>
                <Grid
                    Margin="5"
                    RowDefinitions="20,20"
                    VerticalOptions="Center">
                    <Label
                        FontAttributes="Bold"
                        Text="{Binding Name, StringFormat='Course name: {0}'}"
                        VerticalTextAlignment="Center" />

                    <Label
                        Grid.Row="1"
                        Text="{Binding Path=Total, Source={x:RelativeSource AncestorType={x:Type vm:MyCoursesPageViewModel}}, StringFormat='Students: {0}'}"
                        VerticalTextAlignment="Center" />

                    <Label
                        Grid.RowSpan="2"
                        FontFamily="Mat"
                        FontSize="40"
                        HorizontalTextAlignment="End"
                        Text="{x:Static helpers:IconFont.Read_more}"
                        VerticalTextAlignment="Center" />
                </Grid>
            </Border>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

</Grid>`

Can everyone please update to 8.0.1, this release should fix all the issues we are seeing with data binding!

You can migrate normally now, I’ve added a little XCT to MCT migration guide on the TouchBehavior docs incase it is of use to anyone!

To answer both of your questions @eduardoagr, @r-work we have to reference something else on the view, ie the page or indeed a parent view because the TouchBehavior itself has no BindingContext. In XCT it did because it was an attached effect, the current MCT implementation uses a PlatformBehavior which does not set the BindingContext, this is following Maui documentation guidelines (see article).

So whilst other things like TapGestureRecognizer will work as expected, the TouchBehavior won’t unless you set its binding context through an x:Reference and invoke it that way.

Same issue, except I’m adding the touch behavior to a Frame.

This seems to be related to the Command property binding, if you do not set it, it won’t crash.

Output window:

[mono-rt] [ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: Operation is not valid due to the current state of the object.
[mono-rt]    at Microsoft.Maui.Controls.Binding.ApplyRelativeSourceBinding(BindableObject targetObject, BindableProperty targetProperty, SetterSpecificity specificity) in D:\a\_work\1\s\src\Controls\src\Core\Binding.cs:line 152
[mono-rt]    at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_0(Object state)
[mono-rt]    at Android.App.SyncContext.<>c__DisplayClass2_0.<Post>b__0() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.App/SyncContext.cs:line 36
[mono-rt]    at Java.Lang.Thread.RunnableImplementor.Run() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Java.Lang/Thread.cs:line 36
[mono-rt]    at Java.Lang.IRunnableInvoker.n_Run(IntPtr jnienv, IntPtr native__this) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net8.0/android-34/mcw/Java.Lang.IRunnable.cs:line 84
[mono-rt]    at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V(_JniMarshal_PP_V callback, IntPtr jnienv, IntPtr klazz) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:line 26