Hello, 各位 iT 邦幫忙 的粉絲們大家好~~~
在本系列文會利用目前 Visual Studio 內建的專案樣本建立一個初始的 .NET MAUI 專案,並且透過此 .NET MAUI 專案來把 TopStore App 的開發從 Xamairn.Forms 轉換到 .NET MAUI 上進行。
本篇是 Re: 從零改成用 .NET MAUI 技術來繼續過去用 Xamarin 開發的一個 App : TopStore 系列 系列文的 EP21。
在前一回調整完 interface 然後把 DbService 實作完畢後,接著就可以來撰寫 GoodsPage 要用的 ViewModel 類別了。
在原本的 "ViewModels" 資料夾底下,加入一個新類別:

命名為 "GoodsPageViewModel":

完成後會看到此預設新增出來的類別範本:

手動調整一下,變成新式的寫法:

接著調整 public partial 與繼承 BasePageViewModel 類別:
在 GoodsPageViewModel 類別當中設計一個 _goods 的私有欄位,另外掛上 [ObservableProperty] 的這個 Attritube ,完成後結果如下:
[ObservableProperty]
private ObservableCollection<Models.Product> _goods;
完成結果如下圖所示:

接著就可以開啟 "GoodsPage.xaml.cs" 檔案:
調整類別的預設建構子的封裝描述詞為 private,並撰寫一個可傳入 GoodsPageViewModel 物件資料的建構子,以利使用建構子注入。並在其建構子內部撰寫將傳入的物件資料設定到 GoodsPage 的BindingContext 屬性上:
public GoodsPage(ViewModels.GoodsPageViewModel goodsPageViewModel) : this()
{
BindingContext = goodsPageViewModel;
}
完成結果如下圖所示:

接著 override 掉繼承自 Page 本身設計的 OnAppearing() 頁面生命週期方法:
由於 GoodsPage 本身所設計的繫結屬性 BindingContext 已在前面的建構子當中設定為 GoodsPageViewModel 的資料物件,所以就能讓其 Goods 屬性透過 App.DbService.GetGoods() 去取得 MockData 當中紀錄在 goods 欄位中的多個 Product 資料並設定給 Goods 屬性:
var vm = BindingContext as ViewModels.GoodsPageViewModel;
vm.Goods = App.DataService.GetGoods();
完成結果如下圖所示:
接著打開 "MauiProgram.cs":

找到先前設計的 RegisterAppViewsAndViewModels() 方法,在其中增加 GoodsPage 與 GoodsPageViewMode 的注入使用:
builder.Services.AddSingleton<Pages.GoodsPage>();
builder.Services.AddSingleton<ViewModels.GoodsPageViewModel>();

回到 "GoodPageViewMode.xaml.cs" 在本回前面撰寫在 GoodsPage.xaml.cs 的 OnAppearing() 當中的程式碼:
vm.Goods = App.DataService.GetGoods();
設定中斷點後並執行 "偵錯執行" 此 TopStoreApp 看看,如下圖表示:

點選 "物品項" 這個頁籤時,會觀察到會進入中斷點:

接著會可以看到 vm 本身已經取得了 GoodsPageViewModel 所建立的資料物件:

往下看執行這行後的結果使否有正確取得 "MockData" 當中 hard-code 的 goods 資料:

本 EP 介紹所完成的範例程式碼可在此下載。