Skip to content

NullReferenceException from ShellToolbar OnBackButtonCanExecuteChanged #11401

@Larhei

Description

@Larhei

Description

In a ContentPage I added a BackButtonBehavior to Call a Command in my ViewModel to call

await Shell.Current.Navigation.PopToRootAsync(false);

The shell pops to root which is nice. But after this I get a NullReferenceException from

Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Maui.Controls.ShellToolbar.g__OnBackButtonCanExecuteChanged|11_1(Object sender, EventArgs e)
at CommunityToolkit.Mvvm.Input.AsyncRelayCommand.<set_ExecutionTask>g__MonitorTask|26_0(AsyncRelayCommand this, Task task)
at ObjCRuntime.Runtime.ThrowException(IntPtr gchandle)
at UIKit.UIApplication.UIApplicationMain(Int32 argc, String[] argv, IntPtr principalClassName, IntPtr delegateClassName)
at UIKit.UIApplication.Main(String[] args, Type principalClass, Type delegateClass)
at Program.Main(String[] args) in //Program.cs:line 14

The root page of the shell does not have a BackButtonBehavior. Only the page I navigated from contains a BackButtonBehavior.

By looking at the code of UpdateBackbuttonBehavior in ShellToolbar I would see the following issue.
If someone calls NotifyCanExecuteChanged after navigating to a page containing no BackButtonBehavior it can happen that _backButtonBehavior is null in OnBackButtonCanExecuteChanged.

Steps to Reproduce

  1. Create a new Shell App
  2. Navigate to a Contentpage containing a BackButtonBehavior from root page.
  3. In Backcommand await Shell.Current.Navigation.PopToRootAsync(false);
  4. Force Invocation of CanExecute of the Command that Handled the Back Press and still the _backButtonCommand in ShellToolbar

Link to public reproduction project repository

https://github.com/Larhei/Maui-Issues/tree/main/ShellNavigation

Version with bug

6.0.486

Last version that worked well

Unknown/Other

Affected platforms

iOS, Android

Affected platform versions

iOS and android

Did you find any workaround?

Clearing the Command Binding from the BackButtonBehavior during OnNavigatingFrom in my ContetnPage

protected override void OnNavigatingFrom(NavigatingFromEventArgs args)
{
// Remark: Work around for nullpointer during use of BackButtonBehaviour.
var behaviour = Shell.GetBackButtonBehavior(this);
behaviour?.ClearValue(BackButtonBehavior.CommandProperty);
}

causes a OnBackButtonPropertyChanged in ShellToolbar and this unsubscribes the OnBackButtonCanExecuteChanged handler throwing the exception.

Relevant log output

No response

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions