NavigationPageを使用してページを遷移する際に、遷移先にデータを渡したい場合があります。

ここでは、MainPageとSecondPageがあり、MainPageからSecondPageに遷移する想定で説明をします。

遷移先ページのコードビハインドは以下のように、コンストラクタに引数を持たせます。この例では引数のデータ型をstringにしていますが、実際に使用する場合は、遷移元から受け取るデータの型に合わせてください。

SecondPage.xaml.cs
    namespace NavigationPageSample
{
    public partial class SecondPage : ContentPage
    {
        public SecondPage(string data)
        {
            InitializeComponent();

            // 受け取ったパラメータをラベルに表示
            this.labelPara.Text = data;
        }

        // パラメータ受け渡し用のプロパティを準備
        public string data
        {
            get;
            set;
        }
    }
}

次に、メインページのコードビハインド(MainPage.xaml.cs)を以下のように編集します。

SecondPage_Clickedイベントで、SecondPageに遷移させます。

このときSecondPageのコンストラクタ引数に、遷移先ページに渡したいデータを指定します。

この例では、文字列「Hello」を渡しています。

MainPage.xaml.cs
  namespace NavigationPageSample
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }


        /// [Go to Second Page]ボタンタップ時の処理
        void SecondPage_Clicked(object sender, System.EventArgs e)
        {
            // SecondPageに遷移する
            // コンストラクタの引数に、遷移先に渡したいデータを指定する
            this.Navigation.PushAsync(new SecondPage("Hello"));
        }
    }
}          

実行例を以下に示します。