在 Xamarin.Forms 應用程式中執行導覽

Download Sample 下載範例

在本快速入門中,您將了解如何:

  • 將其他頁面新增至 Xamarin.Forms Shell應用程式。
  • 執行頁面與頁面間的導覽。
  • 使用資料繫結以同步處理使用者介面元素及其資料來源間的資料。

本快速入門會逐步解說如何將能夠儲存單一筆記的跨平臺 Xamarin.Forms Shell 應用程式轉換成能夠儲存多個筆記的應用程式。 最終的應用程式如下所示:

Notes PageNote Entry Page

必要條件

您應該先成功完成先前的快速入門,再嘗試本快速入門。 或者,下載先前的快速入門範例,並使用此範例作為本快速入門的起點。

使用 Visual Studio 更新應用程式

  1. 啟動 Visual Studio。 在開始視窗中,按一下最近使用的專案/方案清單中的 Notes 方案,或按一下 [Open a project or solution] \(開啟專案或方案\),然後在 [開啟專案/方案] 對話方塊中,選取 Notes 專案的方案檔:

    Open Solution

  2. [方案總管] 中,以滑鼠右鍵按兩下 Notes 項目,然後選取 [新增>資料夾]:

    Add New Folder

  3. 在 [方案總管] 中,將新資料夾命名為 Models

    Models Folder

  4. 方案總管 中,選取 Models 資料夾,以滑鼠右鍵按兩下,然後選取 [新增>類別...]:

    Add New File

  5. 在 [ 新增專案 ] 對話框中,選取 [Visual C# 項目 > 類別],將新檔案 命名為 [附注],然後按兩下 [ 新增 ] 按鈕:

    Add Note Class

    這會將名為 Note 的類別新增至 Notes 專案 Models 資料夾。

  6. Note.cs 中,移除所有範本程式碼,並取代為下列程式碼:

    using System;
    
    namespace Notes.Models
    {
        public class Note
        {
            public string Filename { get; set; }
            public string Text { get; set; }
            public DateTime Date { get; set; }
        }
    }
    

    此類別會定義 Note 模型,以儲存應用程式中每個備註的相關資料。

    CTRL+S 將變更儲存至Note.cs

  7. 方案總管 的 Notes 專案中,選取 [檢視] 資料夾,以滑鼠右鍵按兩下,然後選取 [新增>專案...]。在 [新增專案] 對話框中,選取 [Visual C# 專案Xamarin.Forms>>內容頁面],將新檔案命名為 NoteEntryPage,然後按兩下 [新增] 按鈕:

    Add Xamarin.Forms ContentPage

    這會將名為 NoteEntryPage 的新頁面新增至 專案的 Views 資料夾。 此頁面將用於記事專案。

  8. NoteEntryPage.xaml 中,移除所有範本程式碼,並取代為下列程式碼:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Notes.Views.NoteEntryPage"
                 Title="Note Entry">
        <!-- Layout children vertically -->
        <StackLayout Margin="20">
            <Editor Placeholder="Enter your note"
                    Text="{Binding Text}"
                    HeightRequest="100" />
            <!-- Layout children in two columns -->
            <Grid ColumnDefinitions="*,*">
                <Button Text="Save"
                        Clicked="OnSaveButtonClicked" />
                <Button Grid.Column="1"
                        Text="Delete"
                        Clicked="OnDeleteButtonClicked"/>
            </Grid>
        </StackLayout>
    </ContentPage>
    

    此程式代碼會以宣告方式定義頁面的使用者介面,其中包含 Editor 用於文字輸入的 ,以及指示應用程式儲存或刪除檔案的兩 Button 個物件。 兩個 Button 執行個體以水平方式配置在 Grid 中,而 EditorGrid 以垂直方式配置在 StackLayout 中。 此外,Editor 使用資料繫結以繫結至 Note 模型的 Text 屬性。 如需數據系結的詳細資訊,請參閱快速入門深入探討中的數據Xamarin.Forms系結。

    CTRL+S 將變更儲存至 NoteEntryPage.xaml

  9. NoteEntryPage.xaml.cs 中,移除所有範本程式碼,並取代為下列程式碼:

    using System;
    using System.IO;
    using Notes.Models;
    using Xamarin.Forms;
    
    namespace Notes.Views
    {
        [QueryProperty(nameof(ItemId), nameof(ItemId))]
        public partial class NoteEntryPage : ContentPage
        {
            public string ItemId
            {
                set
                {
                    LoadNote(value);
                }
            }
    
            public NoteEntryPage()
            {
                InitializeComponent();
    
                // Set the BindingContext of the page to a new Note.
                BindingContext = new Note();
            }
    
            void LoadNote(string filename)
            {
                try
                {
                    // Retrieve the note and set it as the BindingContext of the page.
                    Note note = new Note
                    {
                        Filename = filename,
                        Text = File.ReadAllText(filename),
                        Date = File.GetCreationTime(filename)
                    };
                    BindingContext = note;
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to load note.");
                }
            }
    
            async void OnSaveButtonClicked(object sender, EventArgs e)
            {
                var note = (Note)BindingContext;
    
                if (string.IsNullOrWhiteSpace(note.Filename))
                {
                    // Save the file.
                    var filename = Path.Combine(App.FolderPath, $"{Path.GetRandomFileName()}.notes.txt");
                    File.WriteAllText(filename, note.Text);
                }
                else
                {
                    // Update the file.
                    File.WriteAllText(note.Filename, note.Text);
                }
    
                // Navigate backwards
                await Shell.Current.GoToAsync("..");
            }
    
            async void OnDeleteButtonClicked(object sender, EventArgs e)
            {
                var note = (Note)BindingContext;
    
                // Delete the file.
                if (File.Exists(note.Filename))
                {
                    File.Delete(note.Filename);
                }
    
                // Navigate backwards
                await Shell.Current.GoToAsync("..");
            }
        }
    }
    

    此程式碼會在頁面的 BindingContext 中,儲存代表單一備註的 Note 執行個體。 類別是以 裝飾, QueryPropertyAttribute 可讓數據透過查詢參數在瀏覽期間傳入頁面。 的第一個自變數QueryPropertyAttribute會指定將接收數據的屬性名稱,而第二個自變數則指定查詢參數標識符。因此,QueryParameterAttribute上述程式代碼中的 會ItemId指定 屬性會從方法呼叫中指定的 URI 接收查詢參數中ItemIdGoToAsync傳遞的數據。 ItemId屬性接著會呼叫 LoadNote 方法,從裝置上的檔案建立Note物件,並將頁面的 設定BindingContextNote 物件。

    按下 SaveButton 時,OnSaveButtonClicked會執行事件處理程式,以將 的內容Editor儲存至具有隨機產生檔名的新檔案,或在更新筆記時儲存至現有的檔案。 在這兩種情況下,檔案都會儲存在應用程式深入探討本機應用程式資料資料夾中。 然後,方法則巡覽回上一頁。 按下 DeleteButton 時,OnDeleteButtonClicked會執行事件處理程式,以刪除檔案,前提是檔案存在,並巡覽回上一頁。 如需流覽的詳細資訊,請參閱殼層快速入門深入探討中的Xamarin.Forms流覽。

    CTRL+S 將變更儲存至NoteEntryPage.xaml.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  10. 方案總管 的 Notes 專案中,開啟 Views 資料夾中的 NotesPage.xaml

  11. NotesPage.xaml 中,移除所有範本程式碼,並取代為下列程式碼:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Notes.Views.NotesPage"
                 Title="Notes">
        <!-- Add an item to the toolbar -->
        <ContentPage.ToolbarItems>
            <ToolbarItem Text="Add"
                         Clicked="OnAddClicked" />
        </ContentPage.ToolbarItems>
    
        <!-- Display notes in a list -->
        <CollectionView x:Name="collectionView"
                        Margin="20"
                        SelectionMode="Single"
                        SelectionChanged="OnSelectionChanged">
            <CollectionView.ItemsLayout>
                <LinearItemsLayout Orientation="Vertical"
                                   ItemSpacing="10" />
            </CollectionView.ItemsLayout>
            <!-- Define the appearance of each item in the list -->
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Label Text="{Binding Text}"
                               FontSize="Medium"/>
                        <Label Text="{Binding Date}"
                               TextColor="Silver"
                               FontSize="Small" />
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </ContentPage>
    

    此程式碼會以宣告方式定義頁面的使用者介面,其包含一個 CollectionView 和一個 ToolbarItem。 會 CollectionView 使用數據系結來顯示應用程式所擷取的任何附註。 選取附註將會巡覽至 NoteEntryPage 可以修改筆記的 。 或者,您也可以按下 ToolbarItem 來建立新的備註。 如需數據系結的詳細資訊,請參閱快速入門深入探討中的數據Xamarin.Forms系結。

    CTRL+S 將變更儲存至 NotesPage.xaml

  12. 方案總管 的 Notes 專案中,展開 Views 資料夾中的 NotesPage.xaml,然後開啟 NotesPage.xaml.cs

  13. NotesPage.xaml.cs 中,移除所有範本程式碼,並取代為下列程式碼:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Notes.Models;
    using Xamarin.Forms;
    
    namespace Notes.Views
    {
        public partial class NotesPage : ContentPage
        {
            public NotesPage()
            {
                InitializeComponent();
            }
    
            protected override void OnAppearing()
            {
                base.OnAppearing();
    
                var notes = new List<Note>();
    
                // Create a Note object from each file.
                var files = Directory.EnumerateFiles(App.FolderPath, "*.notes.txt");
                foreach (var filename in files)
                {
                    notes.Add(new Note
                    {
                        Filename = filename,
                        Text = File.ReadAllText(filename),
                        Date = File.GetCreationTime(filename)
                    });
                }
    
                // Set the data source for the CollectionView to a
                // sorted collection of notes.
                collectionView.ItemsSource = notes
                    .OrderBy(d => d.Date)
                    .ToList();
            }
    
            async void OnAddClicked(object sender, EventArgs e)
            {
                // Navigate to the NoteEntryPage, without passing any data.
                await Shell.Current.GoToAsync(nameof(NoteEntryPage));
            }
    
            async void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                if (e.CurrentSelection != null)
                {
                    // Navigate to the NoteEntryPage, passing the filename as a query parameter.
                    Note note = (Note)e.CurrentSelection.FirstOrDefault();
                    await Shell.Current.GoToAsync($"{nameof(NoteEntryPage)}?{nameof(NoteEntryPage.ItemId)}={note.Filename}");
                }
            }
        }
    }
    

    此程式碼會定義 NotesPage 的功能。 當頁面出現時,即會執行 OnAppearing 方法,這會將擷取自本機應用程式資料資料夾的任何備註填入 CollectionView。 按下 ToolbarItem 即會執行 OnAddClicked 事件處理常式。 這個方法會巡覽至 NoteEntryPage。 選取 CollectionView 中的項目即會執行 OnSelectionChanged 事件處理常式。 這個方法會巡覽至 NoteEntryPage,前提是已選取 中的專案 CollectionView ,將 Filename 選取 Note 的 屬性當做查詢參數傳遞至頁面。 如需流覽的詳細資訊,請參閱快速入門深入探討中的Xamarin.Forms流覽。

    CTRL+S 將變更儲存至NotesPage.xaml.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  14. 在 方案總管 的 Notes 專案中,展開 [AppShell.xaml],然後開啟 [AppShell.xaml.cs]。 將現有程式碼取代成下列程式碼:

    using Notes.Views;
    using Xamarin.Forms;
    
    namespace Notes
    {
        public partial class AppShell : Shell
        {
            public AppShell()
            {
                InitializeComponent();
                Routing.RegisterRoute(nameof(NoteEntryPage), typeof(NoteEntryPage));
            }
        }
    }
    

    此程式代碼會註冊 的路由,此路由 NoteEntryPage不會在殼層視覺階層中表示(AppShell.xaml)。 接著,您可以使用 方法, GoToAsync 使用 URI 型導覽來瀏覽此頁面。

    CTRL+S 將變更儲存至AppShell.xaml.cs

  15. 方案總管Notes 專案中,展開 App.xaml 並開啟 App.xaml.cs。 將現有程式碼取代成下列程式碼:

    using System;
    using System.IO;
    using Xamarin.Forms;
    
    namespace Notes
    {
        public partial class App : Application
        {
            public static string FolderPath { get; private set; }
    
            public App()
            {
                InitializeComponent();
                FolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
                MainPage = new AppShell();
            }
    
            protected override void OnStart()
            {
            }
    
            protected override void OnSleep()
            {
            }
    
            protected override void OnResume()
            {
            }
        }
    }
    
    

    這段程式碼會新增 System.IO 命名空間的命名空間宣告,並新增 string 類型的靜態 FolderPath 屬性宣告。 FolderPath 屬性用於儲存裝置路徑,其為儲存備註資料的路徑。 此外,程式代碼會初始化 FolderPath 建構函式中的 App 屬性,並將 屬性初始化 MainPage 為子類別化 Shell 物件。

    CTRL+S 將變更儲存至App.xaml.cs

  16. 在每個平台上建置並執行專案。 如需詳細資訊,請參閱建置快速入門

    NotesPage,按下 [新增 ] 按鈕以流覽至 NoteEntryPage 並輸入附注。 儲存備註之後,應用程式會巡覽回 NotesPage

    輸入數個不同長度的附注來觀察應用程式行為。 關閉應用程式並重新啟動它,以確保您輸入的筆記已儲存至裝置。

使用 Visual Studio for Mac 更新應用程式

  1. 啟動 Visual Studio for Mac。 在起始視窗中,按一下 [開啟],然後在對話方塊中選取適用於 Notes 專案的方案檔:

    Open Solution

  2. 在 Solution Pad 中,以滑鼠右鍵按下 Notes 專案,然後選取 [新增>資料夾]:

    Add New Folder

  3. 在 [ 新增資料夾] 對話框中,將新資料夾 命名為 Models

    Models Folder

  4. Solution Pad 中,選取 Models 資料夾,以滑鼠右鍵按兩下,然後選取 [新增>類別...]:

    Add New File

  5. 在 [新增檔案] 對話框中,選取 [一般>空白類別],將新檔案命名為 [附注],然後按兩下 [新增] 按鈕:

    Add Note Class

    這會將名為 Note 的類別新增至 Notes 專案 Models 資料夾。

  6. Note.cs 中,移除所有範本程式碼,並取代為下列程式碼:

    using System;
    
    namespace Notes.Models
    {
        public class Note
        {
            public string Filename { get; set; }
            public string Text { get; set; }
            public DateTime Date { get; set; }
        }
    }
    

    此類別會定義 Note 模型,以儲存應用程式中每個備註的相關資料。

    選擇 [檔案>儲存],或按 ⌘ + S,將變更儲存至Note.cs

  7. Solution Pad 中,選取 Notes 專案,以滑鼠右鍵按兩下,然後選取 [ 新增 > 檔案...]。在 [ 新增檔案 ] 對話框中,選取 [Forms > Forms ContentPage XAML],將新檔案 命名為 NoteEntryPage,然後按兩下 [ 新增 ] 按鈕:

    Add Xamarin.Forms ContentPage

    這會將名為 NoteEntryPage 的新頁面新增至 專案的 Views 資料夾。 此頁面將用於記事專案。

  8. NoteEntryPage.xaml 中,移除所有範本程式碼,並取代為下列程式碼:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Notes.Views.NoteEntryPage"
                 Title="Note Entry">
        <!-- Layout children vertically -->
        <StackLayout Margin="20">
            <Editor Placeholder="Enter your note"
                    Text="{Binding Text}"
                    HeightRequest="100" />
            <!-- Layout children in two columns -->
            <Grid ColumnDefinitions="*,*">
                <Button Text="Save"
                        Clicked="OnSaveButtonClicked" />
                <Button Grid.Column="1"
                        Text="Delete"
                        Clicked="OnDeleteButtonClicked"/>
            </Grid>
        </StackLayout>
    </ContentPage>
    

    此程式代碼會以宣告方式定義頁面的使用者介面,其中包含 Editor 用於文字輸入的 ,以及指示應用程式儲存或刪除檔案的兩 Button 個物件。 兩個 Button 執行個體以水平方式配置在 Grid 中,而 EditorGrid 以垂直方式配置在 StackLayout 中。 此外,Editor 使用資料繫結以繫結至 Note 模型的 Text 屬性。 如需數據系結的詳細資訊,請參閱快速入門深入探討中的數據Xamarin.Forms系結。

    選擇 [檔案>儲存],或按 ⌘ + S,將變更儲存至 NoteEntryPage.xaml

  9. NoteEntryPage.xaml.cs 中,移除所有範本程式碼,並取代為下列程式碼:

    using System;
    using System.IO;
    using Notes.Models;
    using Xamarin.Forms;
    
    namespace Notes.Views
    {
        [QueryProperty(nameof(ItemId), nameof(ItemId))]
        public partial class NoteEntryPage : ContentPage
        {
            public string ItemId
            {
                set
                {
                    LoadNote(value);
                }
            }
    
            public NoteEntryPage()
            {
                InitializeComponent();
    
                // Set the BindingContext of the page to a new Note.
                BindingContext = new Note();
            }
    
            void LoadNote(string filename)
            {
                try
                {
                    // Retrieve the note and set it as the BindingContext of the page.
                    Note note = new Note
                    {
                        Filename = filename,
                        Text = File.ReadAllText(filename),
                        Date = File.GetCreationTime(filename)
                    };
                    BindingContext = note;
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to load note.");
                }
            }
    
            async void OnSaveButtonClicked(object sender, EventArgs e)
            {
                var note = (Note)BindingContext;
    
                if (string.IsNullOrWhiteSpace(note.Filename))
                {
                    // Save the file.
                    var filename = Path.Combine(App.FolderPath, $"{Path.GetRandomFileName()}.notes.txt");
                    File.WriteAllText(filename, note.Text);
                }
                else
                {
                    // Update the file.
                    File.WriteAllText(note.Filename, note.Text);
                }
    
                // Navigate backwards
                await Shell.Current.GoToAsync("..");
            }
    
            async void OnDeleteButtonClicked(object sender, EventArgs e)
            {
                var note = (Note)BindingContext;
    
                // Delete the file.
                if (File.Exists(note.Filename))
                {
                    File.Delete(note.Filename);
                }
    
                // Navigate backwards
                await Shell.Current.GoToAsync("..");
            }
        }
    }
    

    此程式碼會在頁面的 BindingContext 中,儲存代表單一備註的 Note 執行個體。 類別是以 裝飾, QueryPropertyAttribute 可讓數據透過查詢參數在瀏覽期間傳入頁面。 的第一個自變數QueryPropertyAttribute會指定將接收數據的屬性名稱,而第二個自變數則指定查詢參數標識符。因此,QueryParameterAttribute上述程式代碼中的 會ItemId指定 屬性會從方法呼叫中指定的 URI 接收查詢參數中ItemIdGoToAsync傳遞的數據。 ItemId屬性接著會呼叫 LoadNote 方法,從裝置上的檔案建立Note物件,並將頁面的 設定BindingContextNote 物件。

    按下 SaveButton 時,OnSaveButtonClicked會執行事件處理程式,以將 的內容Editor儲存至具有隨機產生檔名的新檔案,或在更新筆記時儲存至現有的檔案。 在這兩種情況下,檔案都會儲存在應用程式深入探討本機應用程式資料資料夾中。 然後,方法則巡覽回上一頁。 按下 DeleteButton 時,OnDeleteButtonClicked會執行事件處理程式,以刪除檔案,前提是檔案存在,並巡覽回上一頁。 如需流覽的詳細資訊,請參閱殼層快速入門深入探討中的Xamarin.Forms流覽。

    選擇 [檔案>儲存],或按 ⌘ + S,將變更儲存至NoteEntryPage.xaml.cs

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  10. 在 Solution Pad 的 Notes 專案中,開啟 Views 資料夾中的 NotesPage.xaml

  11. NotesPage.xaml 中,移除所有範本程式碼,並取代為下列程式碼:

    <?xml version="1.0" encoding="UTF-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="Notes.Views.NotesPage"
                 Title="Notes">
        <!-- Add an item to the toolbar -->
        <ContentPage.ToolbarItems>
            <ToolbarItem Text="Add"
                         Clicked="OnAddClicked" />
        </ContentPage.ToolbarItems>
    
        <!-- Display notes in a list -->
        <CollectionView x:Name="collectionView"
                        Margin="20"
                        SelectionMode="Single"
                        SelectionChanged="OnSelectionChanged">
            <CollectionView.ItemsLayout>
                <LinearItemsLayout Orientation="Vertical"
                                   ItemSpacing="10" />
            </CollectionView.ItemsLayout>
            <!-- Define the appearance of each item in the list -->
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Label Text="{Binding Text}"
                               FontSize="Medium"/>
                        <Label Text="{Binding Date}"
                               TextColor="Silver"
                               FontSize="Small" />
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </ContentPage>
    

    此程式碼會以宣告方式定義頁面的使用者介面,其包含一個 CollectionView 和一個 ToolbarItem。 會 CollectionView 使用數據系結來顯示應用程式所擷取的任何附註。 選取附註將會巡覽至 NoteEntryPage 可以修改筆記的 。 或者,您也可以按下 ToolbarItem 來建立新的備註。 如需數據系結的詳細資訊,請參閱快速入門深入探討中的數據Xamarin.Forms系結。

    選擇 [檔案>儲存],或按 ⌘ + S,將變更儲存至 NotesPage.xaml

  12. 在 Solution Pad 的 Notes 專案中,展開 Views 資料夾中的 NotesPage.xaml,然後開啟 NotesPage.xaml.cs。

  13. NotesPage.xaml.cs 中,移除所有範本程式碼,並取代為下列程式碼:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Notes.Models;
    using Xamarin.Forms;
    
    namespace Notes.Views
    {
        public partial class NotesPage : ContentPage
        {
            public NotesPage()
            {
                InitializeComponent();
            }
    
            protected override void OnAppearing()
            {
                base.OnAppearing();
    
                var notes = new List<Note>();
    
                // Create a Note object from each file.
                var files = Directory.EnumerateFiles(App.FolderPath, "*.notes.txt");
                foreach (var filename in files)
                {
                    notes.Add(new Note
                    {
                        Filename = filename,
                        Text = File.ReadAllText(filename),
                        Date = File.GetCreationTime(filename)
                    });
                }
    
                // Set the data source for the CollectionView to a
                // sorted collection of notes.
                collectionView.ItemsSource = notes
                    .OrderBy(d => d.Date)
                    .ToList();
            }
    
            async void OnAddClicked(object sender, EventArgs e)
            {
                // Navigate to the NoteEntryPage, without passing any data.
                await Shell.Current.GoToAsync(nameof(NoteEntryPage));
            }
    
            async void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                if (e.CurrentSelection != null)
                {
                    // Navigate to the NoteEntryPage, passing the filename as a query parameter.
                    Note note = (Note)e.CurrentSelection.FirstOrDefault();
                    await Shell.Current.GoToAsync($"{nameof(NoteEntryPage)}?{nameof(NoteEntryPage.ItemId)}={note.Filename}");
                }
            }
        }
    }
    

    此程式碼會定義 NotesPage 的功能。 當頁面出現時,即會執行 OnAppearing 方法,這會將擷取自本機應用程式資料資料夾的任何備註填入 CollectionView。 按下 ToolbarItem 即會執行 OnAddClicked 事件處理常式。 這個方法會巡覽至 NoteEntryPage。 選取 CollectionView 中的項目即會執行 OnSelectionChanged 事件處理常式。 這個方法會巡覽至 NoteEntryPage,前提是已選取 中的專案 CollectionView ,將 Filename 選取 Note 的 屬性當做查詢參數傳遞至頁面。 如需流覽的詳細資訊,請參閱快速入門深入探討中的Xamarin.Forms流覽。

    選擇 [檔案>儲存] 來儲存變更至NotesPage.xaml.cs (或按 ⌘ + S)。

    警告

    應用程式目前不會建置,因為後續步驟中將會修正的錯誤。

  14. 在 Solution Pad 的 Notes 專案中,展開 [AppShell.xaml],然後開啟 [AppShell.xaml.cs]。 將現有程式碼取代成下列程式碼:

    using Notes.Views;
    using Xamarin.Forms;
    
    namespace Notes
    {
        public partial class AppShell : Shell
        {
            public AppShell()
            {
                InitializeComponent();
                Routing.RegisterRoute(nameof(NoteEntryPage), typeof(NoteEntryPage));
            }
        }
    }
    

    此程式代碼會註冊 的路由,此路由 NoteEntryPage不會在Shell視覺階層中表示。 接著,您可以使用 方法, GoToAsync 使用 URI 型導覽來瀏覽此頁面。

    選擇 [檔案>儲存] 來儲存AppShell.xaml.cs的變更(或按 ⌘ + S)。

  15. 在 Solution Pad 的 Notes 專案中,展開 [App.xaml],然後開啟 [App.xaml.cs]。 將現有程式碼取代成下列程式碼:

    using System;
    using System.IO;
    using Xamarin.Forms;
    
    namespace Notes
    {
        public partial class App : Application
        {
            public static string FolderPath { get; private set; }
    
            public App()
            {
                InitializeComponent();
                FolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
                MainPage = new AppShell();
            }
    
            protected override void OnStart()
            {
            }
    
            protected override void OnSleep()
            {
            }
    
            protected override void OnResume()
            {
            }
        }
    }
    
    

    這段程式碼會新增 System.IO 命名空間的命名空間宣告,並新增 string 類型的靜態 FolderPath 屬性宣告。 FolderPath 屬性用於儲存裝置路徑,其為儲存備註資料的路徑。 此外,程式代碼會初始化 FolderPath 建構函式中的 App 屬性,並將 屬性初始化 MainPage 為子類別化 Shell 物件。

    選擇 [檔案>儲存] 來儲存App.xaml.cs的變更(或按 ⌘ + S)。

  16. 在每個平台上建置並執行專案。 如需詳細資訊,請參閱建置快速入門

    NotesPage,按下 [新增 ] 按鈕以流覽至 NoteEntryPage 並輸入附注。 儲存備註之後,應用程式會巡覽回 NotesPage

    輸入數個不同長度的附注來觀察應用程式行為。 關閉應用程式並重新啟動它,以確保您輸入的筆記已儲存至裝置。

下一步

在本快速入門中,您已了解如何:

  • 將其他頁面新增至 Xamarin.Forms Shell應用程式。
  • 執行頁面與頁面間的導覽。
  • 使用資料繫結以同步處理使用者介面元素及其資料來源間的資料。

請繼續進行下一個快速入門來修改應用程式,使其將數據儲存在本機 SQLite.NET 資料庫中。