UWPのプロジェクトを作成とGridの使い方
2017年4月3日:UWP
Visual Studio Community 2015を使って、UWP(Universal Windows Platform)のプロジェクトを作成する方法について解説します。
プロジェクトの作成
はじめに、メニューから「ファイル->新規作成->プロジェクト」を選択します。続いて、テンプレートからVisual C#のWindowsから、空白のアプリ(ユニバーサルWindows)を選びます。あとは、プロジェクト名をつけ(ここではTestApp)、OKをおします。
以下の画面がでるのでOKをおしましょう。
これでプロジェクトの作成は完了です。
Gridの設置
Gridとは格子という意味です。画面にボタンなどの部品を配置しやすいように、Gridを使用します。初期の段階でGridはついているのでそれを使用しましょう。
右のソリューションエクスプローラーからMainPage.xamlがあるのでダブルクリックします。
すると、UI設計画面が出てきます。
- デバイスを設定します。ここではDesktop(1280×720)を使用します
- 縦か横を指定します。ここでは横を使用します
- ここに画面のコードを表示されます
画面のコーディング
では画面のコードをいじって、Gridを設定します。以下のように画面のコードを変更してください。
<Page x:Class="TestApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestApp" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="100" /> <RowDefinition Height="1*" /> <RowDefinition Height="2*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="200"/> <ColumnDefinition Width="300"/> <ColumnDefinition /> </Grid.ColumnDefinitions> </Grid> </Page>
これにより画面が以下のようにGridで区切られます。
RowDefinitionsが行、ColumnDefinitionが列を定義します。今回両方とも3つあるので、3×3に画面が区切られます。””の数値は幅や高さを意味し、”1*”と”2*”は1:2で分けることを意味します。ColumnDifinitionの最後にWidth設定がないので、のこり全てを意味します。
ボタンなどの部品を設置するときはGrid.Row=”番号”とGrid.Column=”番号”で指定できます(0が最小値)。例えば、以下のようにすると、3 x 3の中心のGridにボタンが設置されます。
<Page x:Class="TestApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestApp" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="100" /> <RowDefinition Height="1*" /> <RowDefinition Height="2*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="200"/> <ColumnDefinition Width="300"/> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="Button"/> </Grid> </Page>
HorizontalAlignment=”Stretch”とVerticalAlignment=”Stretch”により、ボタンをGridの端に合わせるようにしています。Content=”Button”でボタンにButtonと表示されます。以下の図がここで定義したデザインです。
著者:安井 真人(やすい まさと)
@yasui_masatoさんをフォロー