Windowsストア アプリのコード(MainPage.xaml/MainPage.xaml.cs/MainPage.g.i.cs)

前回に続けて、Windowsストアアプリのコードを見てみる。

MainPage.xamlはMetroUIのデザインを行うページとなる。1つのシンプルなページとなり、Windows.UI.Xaml.Controls名前空間のGridクラスが配置されている。従来のWPF/SilverlightではSystem.Windows.Controls名前空間配下だった。

<Page
    x:Class="AppSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:AppSample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

    </Grid>
</Page>

↑MainPage.xamlの中身。


MainPage.xamlはデザインビューで見て編集できる。(App.xamlは「App.xaml をデザイン ビュー内で編集できません」と表示される。)

ツールボックスやプロパティウィンドウからデザインを編集することができる。


なお、細かいデザイン修正を行う場合は、VS2012と同時にインストールされる「Blend for Visual Studio 2012」を使用すると良い。Expression BlendExpression Blend for Windows PhoneのModernUI用のような位置づけとなる。


App.xaml.csの rootFrame.Navigate(typeof(MainPage), args.Arguments)が呼び出されると、MainPageクラスのOnNavigatedToメソッドで画面遷移を受け取れる。NavigationEventArgsクラスから引数を受け取って、MetroにおけるForm_Load的な処理を書くことができる。

// 空白ページ
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    // このページがフレームに表示されるときに呼び出される
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    }
}

↑MainPage.csの中身


なお、OnNavigatedToメソッドは、親クラスのPageにて「protected virtual void OnNavigatedTo(NavigationEventArgs e)」と定義されている。逆にページから離れる時には「protected virtual void OnNavigatingFrom(NavigatingCancelEventArgs e)」をオーバーライドできる。



MainPageのパーシャルクラスMainPage.g.i.csは、ビルドアクション「Page」にて自動生成される。

partial class MainPage : global::Windows.UI.Xaml.Controls.Page
{
    private bool _contentLoaded;

    public void InitializeComponent()
    {
        if (_contentLoaded)
            return;

        _contentLoaded = true;

            global::Windows.UI.Xaml.Application.LoadComponent(
                 this, 
                 new global::System.Uri("ms-appx:///MainPage.xaml"),
                 global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application
            );
    }
}

↑MainPage.g.i.csの中身

xamlファイルを読み込むInitializeComponentが生成されている。