軌道音符狀態

在上一個步驟中,你透過實作 INotifyPropertyChanged 修正了導覽快取的第一個副作用,讓編輯內容能反映在已繫結的文字控制項中。 在導覽時快取頁面的另一個副作用是,新增或刪除新筆記時,筆記集合不會更新。 那是因為先前筆記已儲存,接著再重新讀取所有已儲存的筆記來重建該集合。 你現在會透過追蹤筆記的狀態,然後用狀態來判斷該筆記是否需要新增或刪除來解決這些問題。

Tip

你可以從 GitHub 倉庫的 WinUI 筆記第二部分下載或查看完成的教學程式碼。 若要查看專案開始點與結束點之間的差異,請參閱此提交:updates for part 2

更新收藏集

首先,你需要加入程式碼,以便在新增或刪除筆記時更新集合。 在 AllNotes.cs中,加入 AddNoteRemoveNote 方法,如圖所示。

    public class AllNotes
    {
        public ObservableCollection<Note> Notes { get; set; } = new ObservableCollection<Note>();
        // ...

        // ↓ Add this. ↓
        public void AddNote(Note note)
        {
            // Insert the note at the beginning of the collection.
            Notes.Insert(0, note);
        }

        public void RemoveNote(Note note)
        {
            Notes.Remove(note);
        }
    }

Note

Notes.Add 會將附註加到集合的末尾。 而是放在 Insert 開頭,這樣新音符會先顯示。

在文檔中了解更多:

在註解中新增狀態

記事會在 NotePage 中新增或刪除。 但筆記集合會維持在 AllNotesPage,所以你仍然需要有辦法通知 AllNotesPage 新筆記和刪除筆記。 為此,你會為類別新增一個屬性StateNote。 接著在第三步,你會修改頁面間的導覽,將新增或刪除的筆記作為導覽參數傳遞。

Note.cs中加入一個新的枚舉,稱為 NoteState。 (將它加入在 Note 類別下方,但放在命名空間的大括號內。)

// ↓ Add this. ↓
public enum NoteState
{
    Unset = 0, Unsaved, Saved, Deleted
}

為類別新增一個 State 屬性 Note ,並依照適當方式設定:

  • Unset:新音符
  • Unsaved: 文字已被更改,但未被儲存。
  • Saved: 文字會被修改並儲存到檔案系統。
  • Deleted: 註解已從檔案系統中刪除。
// ↓ Add this. ↓
public NoteState State { get; set; } = NoteState.Unset;

// ↓ Update these. ↓
public string Text
{
    get => _text;
    set
    {
        if (_text != value)
        {
            _text = value;
            // ↓ Add this. ↓
            State = NoteState.Unsaved;
            // ↑ Add this. ↑
            OnPropertyChanged();
        }
    }
}

public async Task SaveAsync()
{
    // Save the note to a file.
    StorageFile noteFile = (StorageFile)await storageFolder.TryGetItemAsync(Filename);
    if (noteFile is null)
    {
        noteFile = await storageFolder.CreateFileAsync(Filename, CreationCollisionOption.ReplaceExisting);
    }
    await FileIO.WriteTextAsync(noteFile, Text);
    // ↓ Add this. ↓
    State = NoteState.Saved;
    // ↑ Add this. ↑
}

public async Task DeleteAsync()
{
    // Delete the note from the file system.
    StorageFile noteFile = (StorageFile)await storageFolder.TryGetItemAsync(Filename);
    if (noteFile is not null)
    {
        await noteFile.DeleteAsync();
    }
    Filename = string.Empty;
    // ↓ Add this. ↓
    State = NoteState.Deleted;
    // ↑ Add this. ↑
}

筆記 State 也必須在首次從檔案系統載入筆記時進行設定。 預設情況下,當在編輯器中建立新筆記但尚未儲存時,State 會是 Unset。 然而,當先前儲存的筆記從檔案系統載入時,其初始 State 應為 Saved

AllNotes.cs中,找到方法 GetFilesInFolderAsync 。 接著更新程式碼,建立一個新的 Note 物件,並將 State 的初始值設為 Saved

Note note = new Note()
{
    Filename = file.Name,
    Text = await FileIO.ReadTextAsync(file),
    Date = file.DateCreated.DateTime, // << Add a comma here.
    // ↓ Add this. ↓
    State = NoteState.Saved
    // ↑ Add this. ↑
};