跟踪笔记状态

在上一步中,通过实现 INotifyPropertyChanged 来修复导航缓存的第一个副作用,以便编辑反映在绑定文本控件中。 在导航时缓存页面的另一个副作用是,添加或删除笔记时,笔记集合不会更新。 这是因为之前会先保存笔记,然后通过重新读取所有已保存的笔记来重建集合。 现在,你将通过跟踪笔记的状态来修复这些问题,然后使用状态来确定是否需要添加或删除笔记。

Tip

可以从 WinUI Notes 第 2 部分的 GitHub 存储库下载或查看本教程的完整代码。 若要查看项目的起点和终点之间的差异,请参阅此提交: 第 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 知道哪些是新增的笔记,哪些是已删除的笔记。 为此,你将向 State 类添加新属性 Note 。 然后,在步骤 3 中,你将修改页面间的导航逻辑,以将新建或删除的笔记作为导航参数传递。

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。 默认情况下,当在编辑器中新建的笔记尚未保存时,StateUnset。 但是,当从文件系统加载之前保存的笔记时,它的 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. ↑
};