Prism MVVM - PageDialogService:操作確認

昨天我們學到了 Prism MVVM  所提供的 PageDialogService 主要提供三揰型式的跳出對話框(Pop-ups Dialog):

  1.  用來顯示警告或是說明訊息
  2.  用來讓使用者作確認選擇(是/否)
  3.  用來讓使用者有多數選項的選擇

加入刪除按鈕

首先在 GoogleMapPage.xaml 中的 ContentPage 的 ToolbarItems 加入繫結 DeleteAddressCommad 命令的刪除按鈕,程式碼如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="Demae.App.Views.GoogleMapPage"
             Title="{Binding AddressModel.Address}">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="刪除" Command="{Binding DeleteAddressCommand}">            
        </ToolbarItem>
    </ContentPage.ToolbarItems>
    <WebView Source="{Binding MapUrl}" />
</ContentPage>

實作命令

接著在對應的 ViewModel 加入 DeleteAddressCommand 實作,如下所示:

private DelegateCommand _deleteAddressCommand;
public DelegateCommand DeleteAddressCommand =>
    _deleteAddressCommand ?? (_deleteAddressCommand = new DelegateCommand(DeleteAddress));

private async void DeleteAddress()
{
    if (await _pageDialogService.DisplayAlertAsync("刪除確認:", "確定刪除這筆地址資料嗎?", "是", "否"))
    {
        try
        {
            if (await _addressService.DeleteAddress(AddressModel.Id))
            {
                await _navigationService.GoBackAsync();
            }
        }
        catch (DemaeApiException e)
        {
            if (e.Connection)
                await _pageDialogService.DisplayAlertAsync("刪除錯誤", e.StatusCode.ToString(), "朕知道了");
            else
                await _pageDialogService.DisplayAlertAsync("連線錯誤", e.StatusCode.ToString(), "朕知道了");
        }
    }
}

請留意:await _pageDialogService.DisplayAlertAsync("刪除確認:", "確定刪除這筆地址資料嗎?", "是", "否") 中的 DisplayAlertAsync() 方法傳入四個字串型別的參數,這三個參數分別為:

  1.  對方框的抬頭文字
  2.  訊息內容
  3.  顯示確定的文字(按此按鈕會回傳 true)
  4.  顯示否定的文字(按此按鈕會回傳 false)

實作 Service

然後再 IAddressService 中加入 Task<bool> DeleteAddress(int id); 如下所示:

using Demae.App.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Demae.App.Services
{
    public interface IAddressService
    {
        Task<List<AddressModel>> GetAddresses();
        Task<bool> DeleteAddress(int id);
    }
}

最後再實作,如下所示:

using Demae.App.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;

namespace Demae.App.Services
{
    public class AddressService : BaseProvider, IAddressService
    {
        public AddressService()
        {
            _baseUrl = "http://demaewebapi.azurewebsites.net/api/";
        }

        public async Task<bool> DeleteAddress(int id)
        {
            return await Delete(string.Format("Addresses/{0}",id));
        }

        public async Task<List<AddressModel>> GetAddresses()
        {
            return await Get<List<AddressModel>>("Addresses");
        }
    }
}

好吧,今天就暫時到此為止。