在此步骤中,让助理提供该应用程序的非视觉部分。 将此更改与 XAML 分开使编译器错误和设计问题更易于隔离。
请求模型和存储服务
使用此提示:
Add the data layer for TaskTally.
- Create a TaskItem model with an ID, title, and completion state.
- Use MVVM Toolkit observable properties.
- Create a TaskStorage service that serializes the task list to JSON.
- Store tasks in ApplicationData.Current.LocalFolder because this is
a packaged WinUI 3 app.
- Return an empty list when the file doesn't exist.
- Serialize save operations so rapid changes don't write the file concurrently.
- Surface real read and write errors to the caller.
- Build the project after the change.
将生成的模型与此实现进行比较:
using CommunityToolkit.Mvvm.ComponentModel;
namespace TaskTally.Models;
public partial class TaskItem : ObservableObject
{
public Guid Id { get; init; } = Guid.NewGuid();
[ObservableProperty]
public partial string Title { get; set; } = string.Empty;
[ObservableProperty]
public partial bool IsComplete { get; set; }
}
该 [ObservableProperty] 属性生成公共属性并更改通知。 类必须 partial 如此,MVVM 工具包源生成器可以添加该代码。
存储服务应如下所示:
using System.Text.Json;
using System.Threading;
using TaskTally.Models;
using Windows.Storage;
namespace TaskTally.Services;
internal static class TaskStorage
{
private const string FileName = "tasks.json";
private static readonly SemaphoreSlim SaveLock = new(1, 1);
public static async Task<IReadOnlyList<TaskItem>> LoadAsync()
{
StorageFile? file =
await ApplicationData.Current.LocalFolder.TryGetItemAsync(FileName) as StorageFile;
if (file is null)
{
return [];
}
string json = await FileIO.ReadTextAsync(file);
return JsonSerializer.Deserialize<List<TaskItem>>(json) ?? [];
}
public static async Task SaveAsync(IEnumerable<TaskItem> tasks)
{
await SaveLock.WaitAsync();
try
{
string json = JsonSerializer.Serialize(tasks, new JsonSerializerOptions
{
WriteIndented = true
});
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
FileName,
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, json);
}
finally
{
SaveLock.Release();
}
}
}
ApplicationData.Current.LocalFolder 此处适用,因为应用具有包标识。
SaveLock 可防止添加、删除和完成操作同时写入同一文件。 如果以后更改分发模型,请再次验证包标识假设,而不是自动复制此存储选项。
了解详细信息: 存储和检索设置和其他应用数据和ApplicationData.LocalFolder。
请求视图模型
接下来,使用此提示:
Add MainPageViewModel.
- Expose an ObservableCollection<TaskItem>.
- Add observable properties for the new-task text and status message.
- Add asynchronous commands to add and delete tasks.
- Disable AddTaskCommand when the title is blank.
- Load tasks once when the page starts.
- Save after add, delete, or completion changes.
- Expose a summary and empty-state property for x:Bind.
- Catch storage exceptions only where the UI can report them.
- Build and fix all warnings.
在响应中检查的主要模式包括:
public ObservableCollection<TaskItem> Tasks { get; } = [];
[ObservableProperty]
public partial string NewTaskTitle { get; set; } = string.Empty;
public string Summary =>
Tasks.Count == 0
? "No tasks yet"
: $"{Tasks.Count(task => !task.IsComplete)} of {Tasks.Count} remaining";
[RelayCommand(CanExecute = nameof(CanAddTask))]
private async Task AddTaskAsync()
{
string title = NewTaskTitle.Trim();
Tasks.Add(new TaskItem { Title = title });
NewTaskTitle = string.Empty;
RefreshTaskState();
await SaveAsync($"Added \"{title}\".");
}
[RelayCommand]
private async Task DeleteTaskAsync(TaskItem task)
{
Tasks.Remove(task);
RefreshTaskState();
await SaveAsync($"Deleted \"{task.Title}\".");
}
private bool CanAddTask() => !string.IsNullOrWhiteSpace(NewTaskTitle);
partial void OnNewTaskTitleChanged(string value)
{
AddTaskCommand.NotifyCanExecuteChanged();
}
检查助手在使用 .Wait() 或 .Result 时是否会阻塞异步工作。 应等待存储操作完成。
视图模型可以在将存储异常转换为供页面显示的消息时捕获这些异常:
private async Task SaveAsync(string successMessage)
{
try
{
await TaskStorage.SaveAsync(Tasks);
ShowStatus(successMessage);
}
catch (Exception ex)
{
ShowStatus($"Changes couldn't be saved: {ex.Message}", hasError: true);
}
}
这不是静默回退:用户会收到错误提示,而且视图模型不会表示保存已成功。
这些命令和 SaveAsync 会调用两个小型辅助函数。
RefreshTaskState 引发计算 Summary 属性的更改通知,以便 UI 在任务列表更改后更新,并 ShowStatus 设置页面绑定到的可观察状态属性:
[ObservableProperty]
public partial string StatusMessage { get; set; } = string.Empty;
[ObservableProperty]
public partial bool IsStatusOpen { get; set; }
[ObservableProperty]
public partial bool HasError { get; set; }
private void RefreshTaskState()
{
OnPropertyChanged(nameof(Summary));
OnPropertyChanged(nameof(HasNoTasks));
}
private void ShowStatus(string message, bool hasError = false)
{
StatusMessage = message;
HasError = hasError;
IsStatusOpen = true;
}
由于 Summary 是计算属性,而不是 [ObservableProperty],因此每当 Tasks 发生更改时,你都需要手动引发它的更改通知。
构建和检查
生成 x64 版本。 将警告视为工作项,尤其是绑定警告和可为 null 的引用警告:
dotnet build -p:Platform=x64
让助理解释它添加的每个软件包。 对于此应用,除了模板中的Windows 应用 SDK和 MVVM 工具包引用之外,不需要任何新包。