Hello, 各位 iT 邦幫忙 的粉絲們大家好~~~
在本系列文會利用目前 Visual Studio 內建的專案樣本建立一個初始的 .NET MAUI 專案,並且透過此 .NET MAUI 專案來把 TopStore App 的開發從 Xamairn.Forms 轉換到 .NET MAUI 上進行。
本篇是 Re: 從零改成用 .NET MAUI 技術來繼續過去用 Xamarin 開發的一個 App : TopStore 系列 系列文的 EP25。
在上一回當中在 GoodsPageViewModel 中來設計完 GoodsPage 當中所需要的 Command 操作,接著就回到 GoodsPage 來進行 XAML 的 Binding 編輯,以利 UI 在控制操作上都能對應到正確的 Command。
在本回當中先針對 CollectionView 所需操控的部分來進行調整。
首先打開 "Pages" 資料夾底下的 "GoodsPage.xaml" 檔案:

接著稍微調整一下 CollectionView 標記當中的 ItemSource 屬性排版位置(非必要,只是為了本文後面截圖方便):
接著加入 SelectionChangedCommand 與 SelectionChangedCommandParameter 的繫結處理,以及 SelectionMode 的設定:
SelectionChangedCommand="{Binding EditCommand}"
SelectionChangedCommandParameter="{Binding Source={RelativeSource Self}, Path=SelectedItem}"
SelectionMode="Single"
完成結果如下圖紅框所示:

接著把焦點移置 SwipeView 當中所設置的 SwipeItem,順便調整一下屬性排版(非必要,只是為了本文後面截圖方便):

接著加入 Command 與 CommandParameter 的繫結處理:
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:GoodsPageViewModel}}, Path=DeleteCommand}"
CommandParameter="{Binding Source={RelativeSource Self}, Path=BindingContext}"
完成結果如下圖紅框所示:

然後再找到設計在這個 SwipeView 當中,包覆在 Grid 版型元件內部,所設置的一個 UI 元件 Button:

因為想善用 CollectionView 這個新 UI 元件,所以在這邊把 Button 給刪除(如下圖藍色框圈起的註解):

接著再找到 Grid 版型元件內部設定 Grid.ColumnDefinition 的 XAML 標記也刪除(如下圖藍色框所示的註解),並且加上 SwipeView.RightItems 的 XAML 標記(如下圖紅框所示):
<SwipeView.RightItems>
<SwipeItems>
<SwipeItem
BackgroundColor="Cyan" Text="下訂單" />
</SwipeItems>
</SwipeView.RightItems>

接著加入 Command 與 CommandParameter 的繫結處理:
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:GoodsPageViewModel}}, Path=MakeOrderCommand}"
CommandParameter="{Binding Source={RelativeSource Self}, Path=BindingContext}"
完成結果如下圖紅框所示:

完成的結果如下:
點選 GoodsPage 當中的一項 Product,正確執行所設計的 Command:

對 GoodsPage 當中的一項 Product 向右滑動,出現在左邊的 "刪除" 項目,點選後正確執行所設計的 Command,再繼續點選 "確定" 後 GoodsPage 的 Product 列表就刪除該 Product:

對 GoodsPage 當中的一項 Product 向左滑動,出現在右邊的 "下訂單" 項目,點選後正確執行所設計的 Command:

本 EP 介紹所完成的範例程式碼可在此下載。
PS 如果對本篇所撰寫的 "Binding" 手法有疑惑的地方,可以到 "2021 鐵人賽的文章 - EP 15: The Button of item in ListView binds Command to ViewModel" 查看了解唷!