星期日, 6月 07, 2020

[X.Form] Messaging Center

打開 Xamarin Shell 官方範本時,發現 Messaging Center 功能,就根據官方文章 - Xamarin.Forms MessagingCenter 來了解並筆記

該範例重點
  • 用 MessagingCenter 傳遞參數至 ViewModel
  • 在 MainPage 內訂閱 Hi,並觸發 DisplayAlert,但是假如取消註冊的話,就不會出現 DisplayAlert

ViewModel
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace MessagingCenterDemo.ViewModel
{
    public class MainPageViewModel
    {
        // ListView 資料來源
        public ObservableCollection<string> Greetings { get; set; }

        public MainPageViewModel()
        {
            Greetings = new ObservableCollection<string>();

            MessagingCenter.Subscribe<MainPage>(this, "Hi", (sender) =>
            {
                Greetings.Add("哈囉");
            });

            MessagingCenter.Subscribe<MainPage, string>(this, "Hi", (sender, arg) =>
            {
                Greetings.Add("哈囉 " + arg);
            });
        }
    }
}
Xaml
<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="MessagingCenterDemo.MainPage">

    <StackLayout Margin="20,35,20,20">
        <Label Text="MessagingCenter 範例"
               FontAttributes="Bold"
               FontSize="Large"
               HorizontalOptions="Center" />
        <Button x:Name="SayHiButton" 
                Text="哈囉"
                Clicked="SayHiButton_Clicked" />
        <StackLayout Orientation="Horizontal">
            <Entry x:Name="NameEntry" 
                   Placeholder="請輸入姓名" 
                   HorizontalOptions="FillAndExpand"/>
            <Button x:Name="SayHiToPersonButton" 
                    Text="跟某人說哈囉"
                    HorizontalOptions="EndAndExpand"
                    Clicked="SayHiToPersonButton_Clicked" />
        </StackLayout>
        <Button x:Name="OnUnsubscribeButton" 
                Text="取消訂閱"
                Clicked="OnUnsubscribeButton_Clicked" />

        <ListView ItemsSource="{Binding Greetings}" />
    </StackLayout>
</ContentPage>
Xaml 畫面顯示

[X.Form] Messaging Center-1



C#
using System;
using System.ComponentModel;
using Xamarin.Forms;
using MessagingCenterDemo.ViewModel;

namespace MessagingCenterDemo
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            BindingContext = new MainPageViewModel();

            // 該訂閱觸發一個訊息提示、第三參數是一個 Action
            MessagingCenter.Subscribe<MainPage, string>(this, "Hi", async (sender, arg) =>
            {
                await DisplayAlert("訊息接收", "參數為 " + arg, "確認");
            });
        }

        private void SayHiButton_Clicked(object sender, EventArgs e)
        {
            MessagingCenter.Send<MainPage>(this, "Hi");
        }

        private void SayHiToPersonButton_Clicked(object sender, EventArgs e)
        {
            string name = NameEntry.Text;
            if (string.IsNullOrEmpty(name))
            {
                DisplayAlert("錯誤", "請填寫姓名欄位", "確認");
                return;
            }

            MessagingCenter.Send<MainPage, string>(this, "Hi", name);
        }

        private async void OnUnsubscribeButton_Clicked(object sender, EventArgs e)
        {
            MessagingCenter.Unsubscribe<MainPage, string>(this, "Hi");
            await DisplayAlert("取消訂閱", "該頁面已經停止訂閱,不會在有訊息提醒出現。但是 ViewModel 仍然會接收新增訊息", "確認");
        }
    }
}

按下 [跟某人說哈囉] 後,會出現訊息提示,說明輸入參數

[X.Form] Messaging Center-2

按下 [取消訂閱],取消 MainPage 訂閱,但目前 ViewModel 訂閱仍存在

[X.Form] Messaging Center-3

再次按下 [跟某人說哈囉],因為之前已經取消 MainPage 訂閱,所以不會有訊息提示,會直接把資料送進 ViewModel 內

[X.Form] Messaging Center-4

沒有留言:

張貼留言