Windows Phoneアプリケーションで別のフォームに表示を切り替える
Windows Phoneアプリケーションで複数のフォームを切り替える方法を紹介します。
UIの作成
新規のWindows Phoneアプリケーションを作成します。画面をわかりやすく留守為、メインページの上部のラベル(TextBlock)をp"MainPage"に変えました。
右側の[ソリューションエクスプローラ]のプロジェクトのノードを選択して右クリックをしポップアップメニューを表示します。ポップアップメニュの[追加]メニューの[新しい項目]サブメニューをクリックします。
新しい項目の追加ダイアログボックスが表示されます。右側の項目の一覧から[Windows Phone 縦向きのページ]を選択します。下部の名前テキストボックスに[PageSub.xaml]を入力します。入力後右下の[追加]ボタンをクリックします。
2枚目の画面(ページ)が追加されました。
上部の[ページ名]ラベル(TextBlock)を[SubPage]に変更しました。キャプションの変更は該当するTextBlockを選択し、Textプロパティを編集して変更できます。
コードの記述
コードを記述します。メインページにボタンを一つ設置します。
ボタンのClickイベントにコードを記述します。
コード全体は以下になります
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace PhoneAppMultiForm
{
public partial class MainPage : PhoneApplicationPage
{
// コンストラクター
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Uri SubPageUri = new System.Uri("/PageSub.xaml", UriKind.Relative);
NavigationService.Navigate(SubPageUri);
}
}
}
サブページにもボタンを配置します。こちらはメインページに戻るボタンです。
ボタンのClickイベントにコードを記述します。コード全体は以下になります。
PageSub.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace PhoneAppMultiForm
{
public partial class PageSub : PhoneApplicationPage
{
public PageSub()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Uri MainPageUri = new System.Uri("/MainPage.xaml", UriKind.Relative);
NavigationService.Navigate(MainPageUri);
}
}
}
アプリケーションの実行
アプリケーションを実行します。下図のメインページが表示されます。
[ページ切り替え]ボタンをクリックするとサブページが表示されます。(下図)
[もどる]ボタンをクリックすると元のページに戻ります。
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。