我們昨日創建了MAUI的getAll和add Todo方法,我們今天來試著將我們的App加入update和delete的方法
...
[RelayCommand]
public async void EditTodo(TodoItemModel todoItemModel)
{
var navParam = new Dictionary<string, object>();
navParam.Add("TodoItem", todoItemModel);
await AppShell.Current.GoToAsync(nameof(AddTodoPage), navParam);
}
[RelayCommand]
public async void DeleteTodo(TodoItemModel todoItemModel)
{
var del = await _todoService.DeleteTodo(todoItemModel);
if(del > 0) {
GetTodoList();
}
}
}
}
修改一下model,並在模擬器中刪除反安裝appTodo\Models\TodoItemModel.cs
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Todo.Models
{
public class TodoItemModel
{
[PrimaryKey, AutoIncrement]
public int TodoId { get; set; }
public string Title { get; set; }
public bool IsDone { get; set; }
}
}
加入按鈕並綁定
TodoPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:models="clr-namespace:Todo.Models"
xmlns:viewModels="clr-namespace:Todo.ViewModels"
x:DataType="viewModels:TodoListViewModel"
x:Class="Todo.TodoPage"
Title="TodoPage">
<VerticalStackLayout Margin="10">
<Label
Text="Welcome to .NET MAUI!"
VerticalOptions="Center"
HorizontalOptions="Center" />
<Button Text="Go to Add Page" Clicked="ButtonClicked"/>
<CollectionView ItemsSource="{Binding Todos}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:TodoItemModel">
<Frame>
<HorizontalStackLayout Spacing="10" HorizontalOptions="Center">
<Label Text="{Binding Title}" />
<CheckBox IsChecked="{Binding IsDone}"/>
<Button Text="Delete"
Command="{Binding Source={x:RelativeSource AncestorType={x:Type viewModels:TodoListViewModel}},Path=DeleteTodoCommand}"
CommandParameter="{Binding .}"/>
<Button Text="Edit"
Command="{Binding Source={x:RelativeSource AncestorType={x:Type viewModels:TodoListViewModel}},Path=EditTodoCommand}"
CommandParameter="{Binding .}"/>
</HorizontalStackLayout>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ContentPage>
(刪除後重安裝app會出現no sqlite在重啟一次就沒了,可能是我們的app初始化有問題,之後要修改)
這邊我們測試
今天簡單的實現刪除和編輯功能,明天我們接著來完善我們的Todo App