【Windows 10アプリ】Hello worldアプリを作ってみる
最初のアプリ
前回まででWindows 10アプリを開発する環境が整ったので一番最初のアプリを作ってみたいと思います。 とは言っても一番最初なのでHellow world的なアプリを作ってみます。 Windows デベロッパー センター内に"Hello, world" アプリを作成する (XAML)という記事を見つけたのでやってみました。 TextBoxが1つあり、そこにテキストを入力するとTextBlockに「Hello, {入力した文字列}!」と表示するだけのシンプルなアプリです。
UIの編集
空のプロジェクトを作成するとMainPage.xamlというファイルが作成されます。ここにUI部品を貼り付けていきます。 記事では最終的に下記のような構造となっています。
<Page x:Class="HelloWorld.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:HelloWorld" 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}"> <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualState x:Name="wideState"> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="641" /> </VisualState.StateTriggers> </VisualState> <VisualState x:Name="narrowState"> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="0" /> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="inputPanel.Orientation" Value="Vertical"/> <Setter Target="inputButton.Margin" Value="0,4,0,0"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <StackPanel x:Name="contentPanel" Margin="8,32,0,0"> <TextBlock Text="Hello, world!" Margin="0,0,0,40"/> <TextBlock Text="What's your name?"/> <StackPanel x:Name="inputPanel" Orientation="Horizontal" Margin="0,20,0,20"> <TextBox x:Name="nameInput" Width="280" HorizontalAlignment="Left"/> <Button x:Name="inputButton" Content="Say "Hello"" Click="Button_Click"/> </StackPanel> <TextBlock x:Name="greetingOutput"/> </StackPanel> </Grid> </Page>
この中で重要なところはVisualStateManagerを使用して見た目を変更していることでしょうか。 ウィンドウ幅が641px以上の場合は特に見た目を変更しません。 StackPanelタグ内に記述した通りに表示されます。 一方、ウィンドウ幅が0px以上640px以下の場合はinputPanelというStackPanelのOrientationプロパティをVerticalにし、ボタンの上マージンを設定しています。
ボタンクリック時のイベントを実装
見た目ができたので後はボタンがクリックされた時の処理を記述します。 inputButtonのプロパティウィンドウのClickイベントハンドラーに「Button_Click」と入力してEnterキーを押すとMainPage.xaml.csファイルに 空のButton_Clickメソッドが追加されるのでその中に処理を記述します。 最終的に下記のような実装となりました。
private void Button_Click(object sender, RoutedEventArgs e) { greetingOutput.Text = "Hello, " + nameInput.Text + "!"; }
TextBoxに入力された文字列を使って文字列を整形し、TextBlockに表示しているだけですね。
エミュレータで動かしてみる
アプリが出来たのでモバイルエミュレータで動かしてみましょう。 6インチのエミュレータで動かしてみます。
縦表示
縦表示だとTextBlockがTextBoxの下に配置されています。
横表示
横表示だとTextBlockはTextBoxの右に表示されています。 ちゃんとVisualStateManagerによる見た目の変更が効いていることがわかります。
まとめ
今回は最初のアプリとしてすごくシンプルなアプリを作ってみました。 実際にコーディングしたロジックがエミュレータや実機上で動くのを見ると楽しいですね!
今回は以上っす。