Xamarin 窗体导航问题

本文关键字:问题 导航 窗体 Xamarin | 更新日期: 2023-09-27 18:37:08

我正在开发Xamarin Forms应用程序,遇到了一个问题。

导航系统似乎有点不对劲。我正在使用根导航页面来托管我的页面,它一直工作正常,除了......

我有一个带有项目列表的子页面。点击时,每个项目都应在单独的页面上显示有关其自身的信息(无论是否为模态)。

但是,它仅在第一次有效。第二次我尝试检查一个条目时,它似乎加载了两次(字体更粗,有点鬼),当我按下时,一个图层留在后面,而另一个图层随着关闭动画移动(这就是为什么我认为它被加载了两次)。

代码如下:

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' 类仅将 BindingContext 设置为传递的 Note 对象。Note 类有四个属性:字符串标题、字符串日期(其代码返回字段是 DateTime 对象,转换发生在 getter-setter 中)、字符串作者和字符串内容。所有详细信息都正确显示。

唯一的问题是第二次检查 - 它只是拒绝正常工作。可能是什么问题?

Xamarin 窗体导航问题

当您

关闭模态时,OnAppearing会再次被调用。

这意味着下次点击 ItemSelected 时,代码将运行两次。

不过,仅在 iOS 上。

您还可以

设置一个变量来检查页面是否首次加载。

protected override void OnAppearing()
{
   if (_isFirstLoad) {
   //-- create your list
   //-- _isFirstLoad = true;
   }
}