You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

57 lines
1.5 KiB

@page "/todo"
@using BlazorHybridWithMAUI.Data
@using System.Text.Json
<h3>Todo (@_todos.Count(t => !t.IsDone))</h3>
<button @onclick="Save">Save</button>
<button @onclick="Load">Load</button>
<ul class="list-unstyled">
@foreach (var todo in _todos)
{
<li>
<input type="checkbox" @bind="todo.IsDone" />
<input @bind="todo.Title"/>
</li>
}
</ul>
<input placeholder="Something todo" @bind="newTodo"/>
<button @onclick="AddTodo">Add todo</button>
@code {
private const string SAVE_FILE_NAME = "todo.json";
private List<TodoItem> _todos = new List<TodoItem>();
private string? newTodo;
private void AddTodo()
{
if (string.IsNullOrEmpty(newTodo))
return;
_todos.Add(new TodoItem() { Title = newTodo });
newTodo = string.Empty;
}
private async Task Save()
{
var contents = JsonSerializer.Serialize(_todos);
var path = Path.Combine(FileSystem.AppDataDirectory, SAVE_FILE_NAME);
File.WriteAllText(path, contents);
await App.Current.MainPage.DisplayAlert("List Saved.", $"List has been saved to {path}", "OK");
}
private void Load()
{
var path = Path.Combine(FileSystem.AppDataDirectory, SAVE_FILE_NAME);
if (!File.Exists(path))
return;
var contents = File.ReadAllText(path);
var savedItems = JsonSerializer.Deserialize<List<TodoItem>>(contents);
_todos.Clear();
_todos.AddRange(savedItems);
}
}