Xamrin.Forms: MessagingCenter


Forms側にボタンを作ってタップしたらOS情報をラベルに記載

  • ボタンがクリックされた時に button_click イベントを送信する
  • サブスクライバに SetLabel を読んでもらう
using System;

using Xamarin.Forms;

namespace PushNotification
{
  ///
  /// MainPage = new MainContent();
    public class MainContent : ContentPage
    {
        Label  _label = new Label();
        Button _button = new Button{ Text = "Tap Here"};

        public MainContent ()
        {
            Content = new StackLayout {
                Children = {
                    _label, _button
                },        
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Center                    
            };

            this._button.Clicked +=  (object sender, EventArgs e) =>
            {
                MessagingCenter.Send(this, "button_click");
            };
        }

        public void SetLabel(string msg){
            _label.Text = msg;
        }
    }
}

サブスクライバ

  • button_click をサブスクライブする
  • MainContent.SetLabel(msg) でOS情報を渡す

Android

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

using Xamarin.Forms;

namespace PushNotification.Droid
{
    [Activity (Label = "PushNotification.Droid",
   Icon = "@drawable/icon", MainLauncher = true,
   ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            global::Xamarin.Forms.Forms.Init (this, bundle);

            LoadApplication (new App ());

            MessagingCenter.Subscribe<MainContent> (this, "button_click", (content) => {
                content.SetLabel(string.Format("{0} {1}",
                    Android.OS.Build.VERSION.Release,
                    DateTime.Now.ToLongTimeString() ));
            });
        }
    }
}

iOS

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

using Xamarin.Forms;

namespace PushNotification.iOS
{
    [Register ("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init ();

            LoadApplication (new App ());

            MessagingCenter.Subscribe<MainContent> (this, "button_click", (content) => {
                content.SetLabel(string.Format("{0} {1}",
                    new NSProcessInfo().OperatingSystemVersionString,
                    DateTime.Now.ToLongTimeString() ));
            });

            return base.FinishedLaunching (app, options);
        }
    }
}