WPFアプリケーションを作る上で、ユーザーインターフェース(UI)の定義には XAML(ザムル) が使われます。
HTMLやXMLに似た構文ながら、WPFの機能と密接に連携しており、「設計とロジックの分離」というMVVMアーキテクチャの実現にも不可欠です。
この記事では、WPFにおけるXAMLの役割、基本構文、レイアウト制御、バインディング、リソース管理、さらにはMVVM連携の基礎までを一気に解説します。
1. なぜXAMLを使うのか?
XAMLは、WPFにおいて「UI設計を視覚的・宣言的に定義できる」手段です。
主なメリットは次の通りです:
UI構築をコードで全て書くこともできますが、保守性・再利用性の観点からXAMLは圧倒的に有利です。
2. XAMLの基本構造と文法
ウィンドウの基本構造
<Window xClass="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlnsx="http://schemas.microsoft.com/winfx/2006/xaml"
Title="メインウィンドウ" Height="300" Width="400">
<Grid>
<Button Content="クリック" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
xmlns
:WPF標準のUI要素(Button、TextBlockなど)を使うための名前空間
xmlns:x
:x:Name や x:Class などXAML構文上の補助
<Grid>
:UI要素のレイアウトコンテナ(後述)
属性とプロパティ要素の違い
<Button Content="保存" Width="100" />
<Button Width="120">
<ButtonContent>
<StackPanel>
<TextBlock Text="保存" />
<TextBlock Text="(ローカル)" />
</StackPanel>
</ButtonContent>
</Button>
3. よく使われるレイアウトパネル
StackPanel(縦や横に積む)
<StackPanel Orientation="Vertical" Margin="10">
<TextBlock Text="名前" />
<TextBox Width="200"/>
<Button Content="登録" />
</StackPanel>
Grid(表形式レイアウト)
<Grid>
<GridRowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*" />
</GridRowDefinitions>
<GridColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*" />
</GridColumnDefinitions>
<TextBlock Text="ID:" GridRow="0" GridColumn="0" />
<TextBox GridRow="0" GridColumn="1" />
<TextBlock Text="パスワード:" GridRow="1" GridColumn="0" />
<PasswordBox GridRow="1" GridColumn="1" />
</Grid>
XAMLの最大の強みのひとつが データバインディング です。
<TextBox Text="{Binding UserName}" />
<Button Content="ログイン" Command="{Binding LoginCommand}" />
DataContextとは?
WPFでは DataContext
がバインディングの起点になります。コードビハインドで次のようにViewModelをセットします。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
ViewModel は通常、INotifyPropertyChanged
を実装し、プロパティ変更をUIに通知します(CommunityToolkit.Mvvm使用で簡潔に)。
5. イベント vs コマンド
従来のイベント処理(XAMLにC#メソッド名を書く)
<Button Content="押す" Click="Button_Click" />
→ この方法でも動きますが、MVVMパターンでは避けるべきです。
コマンド(CommandプロパティによるMVVM的記述)
<Button Content="押す" Command="{Binding ClickCommand}" />
→ ViewModel側に ICommand
を実装したプロパティが必要です。
CommunityToolkit.Mvvm を使えば次のように簡潔に記述できます:
[RelayCommand]
private void Click() {
}
6. スタイルとリソース
<WindowResources>
<Style TargetType="Button">
<Setter Property="Margin" Value="5"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</WindowResources>
<Button Content="OK"/>
<Button Content="キャンセル"/>
→ すべてのボタンに共通の見た目が適用されます。
リソースの参照方法には StaticResource
と DynamicResource
があり、用途によって使い分けます。
7. よくあるエラーと対処法
症状 |
原因 |
対処法 |
赤波線が出る |
名前空間や型名のミス |
x:Class とコードビハインドの整合性を確認 |
デザイナがクラッシュ |
Visual Studioの不具合 |
プロジェクトを一度ビルドして再表示 |
バインディングが効かない |
DataContext 未設定 or プロパティ通知不足 |
ViewModel構成を再確認 |
8. サンプル:ミニログイン画面の全体構成
<StackPanel Margin="20">
<TextBlock Text="ユーザー名" />
<TextBox Text="{Binding UserName}" Width="200" />
<TextBlock Text="パスワード" />
<PasswordBox xName="PasswordInput" Width="200" />
<Button Content="ログイン" Command="{Binding LoginCommand}" Margin="0,10,0,0"/>
</StackPanel>
ViewModel(CommunityToolkit使用):
public partial class LoginViewModel : ObservableObject
{
[ObservableProperty]
private string userName;
[RelayCommand]
private void Login()
{
}
}
9. おわりに:XAMLが“読める”とUIはもっと楽しくなる
WPFは「ロジックと見た目を切り分けて設計する」思想を徹底できる稀有なフレームワークです。
XAMLに慣れてくると、UIがコードから解き放たれ、開発効率も表現力も格段に向上します。
次回は、「スタイルとテンプレート入門」 に進み、再利用性とデザインの自由度をさらに高めていきましょう。