dotnet / maui-samples

Samples for .NET Multi-Platform App UI (.NET MAUI)
https://dot.net/maui
MIT License
3k stars 1.24k forks source link

Command bindings are not re-established when navigating back and forth in UIInterface samples #484

Open TheKoren opened 1 month ago

TheKoren commented 1 month ago

Due to how the navigation stack is being managed the command bindings are not properly refreshed when navigating between views in UserInterface samples.

Expected Behavior

Navigation is possible between different Views without reloading the application.

Possible Solution

I've tried an approach where i reset the 'BindingContext' in the 'OnAppearing' method and it solves the problem.

Steps to Reproduce

  1. Open 'UserInterface\Layouts\StackLayoutDemos' solution.
  2. Run the application.
  3. Select the AlignmentPage demo.
  4. Navigate back to the MainPage using the back button.
  5. Try to select any of the demos available from MainPage UI. Nothing should happen in it's current form.

Possible Implementation

Adding this to the MainPage solves the problem.

protected override void OnAppearing()
{
    base.OnAppearing();
    BindingContext = null;
    BindingContext = this;
}
jfversluis commented 1 month ago

I don't think I fully understand the problem, but looking at the solution I highly doubt that this is something we should want to be honest. Doesn't really seem to be a great practice. Refreshing the whole BindingContext will reevaluate all the bindings on a page and doing so during the appearing event might cause sluggish, hanging user interfaces.

Could you maybe elaborate a bit more on what the problem is that you're seeing? Also is this happening on one platform or all the platforms?

gcadmes-extron commented 2 weeks ago

@jfversluis Navigation only works once. This sample for example, once you click on any of the navigable items in the TableView, navigating back to the MainPage, the navigable items are no longer navigable. Coincidently, this also happens on any other sample that use the same navigation implementation.

Using the latest VS, download your sample as a .zip file and this should be easily reproducible.

Fwiw, clicking the first item in the TableView"Draw Shapes" actually crashes the app.

TheKoren commented 2 weeks ago

For some reason I haven't got the notifications for this thread, but the issue is exactly what @gcadmes-extron wrote above.

If refreshing the BindingContext is not optimal, we could just change the implementation of the navigation command. I've used a different solution for it in my own projects, and they work just fine.

Current version:

NavigateCommand = new Command<Type>(
                async (Type pageType) =>
                {
                    Page page = (Page)Activator.CreateInstance(pageType);
                    await Navigation.PushAsync(page);
                });