WinUI3アプリケーションでウィンドウにボタンやテキストボックスを配置する手順を紹介します。
事前準備
Visual Studioの導入や、Windows App SDKのVisual Studio拡張のインストールをします。
インストール手順は以下の記事を参照してください。
また、XAMLのタグを調べるための WinUI 3 Gallery アプリをインストールします。
インストール手順は以下の記事を参照してください。
手順
プロジェクトの作成
プロジェクトを作成します。新しいプロジェクトの作成ダイアログで WinUI3のプロジェクトを選択します。
今回は[空のアプリ、パッケージ化 (デスクトップの WinUI 3)]のテンプレートを選択します。
プロジェクト名を設定します。
WinUI 3のプロジェクトが作成できました。
ウィンドウへのコントロールの配置
MainWindows.xamlを開きます。
コントロールのXAMLタグを確認します。WinUI 3 Galleryを起動します。
左側のメニューの[Text]の項目をクリックします。下図の画面が表示されます。右側のエリアの[TextBox]のタイルをクリックします。
TextBoxのサンプルコントロールの画面が表示されます。
[A Simple TextBox]の項目の、[Source code]のタイルをクリックします。
下に枠が開き、テキストボックスを表現する、XAMLのコードが表示されます。
ボタンのコードも確認します。WinUI 3 Galleryのトップ画面の左側のメニューの[Basic Input]の項目をクリックします。
下図の画面が表示されます。右側のエリアの[Button]のタイルをクリックします。
Buttonのサンプルコントロールの画面が表示されます。
[A simple Button with text content.]の項目の[Source code]のタイルをクリックします。
下に枠が開き、テキストボックスを表現する、XAMLのコードが表示されます。
今回は、ハイライトされたボタンにしたいので、右側のエリアを下にスクロールし、[Accent style applied to Button.]の
セクションの[Source code]の枠を開いてコードを確認します。ボタンのコントロールに
Style="{StaticResource AccentButtonStyle}"
を
追加すればよいことがわかります。
調べたXAMLコードをMainWindows.xamlに記述します。
以下のコードに変更しました。
テキストボックスを3つ配置し、ボタンをAccent styleに設定しています。
<Window
x:Class="SimpleButtonAndTextBoxApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SimpleButtonAndTextBoxApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
</StackPanel>
</Window>
<Window
x:Class="SimpleButtonAndTextBoxApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SimpleButtonAndTextBoxApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox AutomationProperties.Name="TextBox1"/>
<TextBox AutomationProperties.Name="TextBox2"/>
<Button Style="{StaticResource AccentButtonStyle}" x:Name="myButton" Click="myButton_Click">Click Me</Button>
<TextBox AutomationProperties.Name="TextBox3"/>
</StackPanel>
</Window>
プロジェクトの実行
プロジェクトを実行します。下図のウィンドウが表示されます。テキストボックスが3つ表示され、
ボタンがハイライトカラーのボタンになっていることが確認できます。
テキストボックスに文字列を入力してみます。動作も問題なさそうです。
ボタンをクリックします。ボタンのキャプションが "Clicked"に変わりました。
WinUI3 のウィンドウにコントロールを配置できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2022-08-09
作成日: 2022-08-09