fonix232 fonix232 - 6 days ago 5
C# Question

Xamarin Forms navigation issue

I'm working on a Xamarin Forms app, and I've ran into an issue.

The navigation system seems to be off a bit. I'm using a root NavigationPage to host my pages, and it works fine all time, except...

I have a sub-page with a list of items. When tapped, each item should display information about itself, on a separate page (let it be modal or not).

However, it only works the first time. The second time I try to check an entry, it seemingly loads it twice (font is thicker and a bit ghosty), and when I press back, one layer stays behind while the other moves with the close animation (that's why I think it was loaded twice).

The code is the following:

public partial class NotesPage : ContentPage {
protected override void OnAppearing()
{
base.OnAppearing();

NotesList.ItemsSource = VM.Notes; // VM is my ViewModel, NotesList is a ListView defined in XAML
NotesList.ItemSelected += async (sender, e) =>
{
if (e.SelectedItem == null) return;
await Navigation.PushAsync(new NoteDetails((Note)e.Item));
((ListView)sender).SelectedItem = null;
};
}
}


<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Views.Notes.NoteDetails">
<StackLayout>
<Label Text="{Binding Title}" />
<Label Text="{Binding Date}" />
<Label Text="{Binding Author}" />
<Label Text="{Binding Content}" />
</StackLayout>
</ContentPage>


NoteDetails' class only sets the BindingContext to the Note object passed.
The Note class has four properties: a String Title, a String Date (its code-back field is a DateTime object, conversion happens in the getter-setter), a String Author and a String Content. All the details are displayed properly.

The only issue is this second-time checking - it simply refuses to work properly.
What can be the problem?

Answer

OnAppearing gets called again when you close a modal.

This means that next time you hit the ItemSelected, the code will be run twice.

Only on iOS though.

Comments