Share via


Windows Presentation Foundation の概要

更新 : 2007 年 11 月

このチュートリアルでは、ほとんどの Windows Presentation Foundation (WPF) アプリケーションに共通の要素を含む WPF アプリケーションの開発の概要について説明します。このような共通の要素には、Extensible Application Markup Language (XAML) マークアップ、分離コード、アプリケーション定義、コントロール、レイアウト、データ バインディング、スタイルなどがあります。

このトピックには次のセクションが含まれています。

  • 概要
  • 必要条件
  • アプリケーション コード ファイルの作成
  • アプリケーションのビルドと実行
  • レイアウトの追加
  • コントロールの追加
  • イメージとタイトルの追加
  • イベントを処理するコードの追加
  • ExpenseReportPage の UI の作成
  • コントロールにスタイルを適用するコードの追加
  • コントロールへのデータのバインド
  • コントロールへのデータの接続
  • データ テンプレートを使用したデータへのスタイルの追加
  • 最適な使用方法
  • 次の内容
  • 関連トピック

概要

このチュートリアルでは、次の手順に従って、簡単な WPF アプリケーションを作成していきます。

  • XAML マークアップを定義して、アプリケーションのユーザー インターフェイス (UI) の外観を設計します。

  • アプリケーションの動作を構築するコードを記述します。

  • アプリケーション定義を作成して、アプリケーションを管理します。

  • コントロールおよびレイアウトを追加してアプリケーションの UI を構成します。

  • アプリケーションの UI 全体で一貫性のある外観を作成するためのスタイルを作成します。

  • UI をデータへバインドして、データから UI を設定し、データと UI の同期を維持します。

このチュートリアルの終わりには、選択した個人の経費報告書を表示するスタンドアロンの Windows アプリケーションが完成します。このアプリケーションは、ブラウザ スタイルのウィンドウでホストされる複数の WPF ページから構成されます。

このチュートリアルで使用するサンプル コードは、C# と Microsoft Visual Basic .NET の両方が用意されています。「Windows Presentation Foundation アプリケーションの構築の概要」を参照してください。

必要条件

このチュートリアルで開発されるアプリケーションをビルドするには、Microsoft .NET Framework および Windows ソフトウェア開発キット (SDK) の両方がインストールされている必要があります。

これらがインストールされている場合は、このアプリケーションをコマンド ウィンドウからビルドできます (ただし、必要に応じて、Microsoft Visual Studio のような 統合開発環境 (IDE) を使用することもできます)。コマンド プロンプトからビルドするには、Windows ソフトウェア開発キット (SDK) と共にインストールされるコマンド ウィンドウを使用する必要があります。これは、メニューの次の場所にあります。

  • [スタート] メニュー | [すべてのプログラム] | [Microsoft Windows SDK] | [CMD Shell]

または、次の手順に従って Windows コマンド プロンプトを開くことができます。

  1. [スタート] ボタンをクリックし、[ファイル名を指定して実行] をクリックします。

  2. 次の URL を入力します。

    C:\WINDOWS\system32\cmd.exe /E:ON /V:ON /T:0E /K "C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\SetEnv.Cmd"

  3. [OK] をクリックします。

SetEnv.cmd は、コマンド プロンプトから WPF アプリケーションをビルドするために必要な環境を設定します。

アプリケーション コード ファイルの作成

この手順では、アプリケーション定義、2 つのページ、および 1 つのイメージが含まれるアプリケーション インフラストラクチャを作成します。

  1. App.xaml という新しい XAML マークアップ ファイルを作成します。このファイルは、WPF アプリケーションを定義し、アプリケーションの起動時に自動的に表示する UI を指定するためにも使われます。この例では、次の手順で作成する HomePage.xaml を指定しています。この XAML マークアップは、次のようになります。

    <Application 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      StartupUri="HomePage.xaml">
    </Application>
    
  2. HomePage.xaml という新しい XAML マークアップ ファイルを作成します。このファイルは、アプリケーションの起動時に最初に表示されるページになります。HomePage.xaml には個人の一覧が表示され、ユーザーはここで経費報告書の表示対象となる個人を選択できます。HomePage.xaml に Page 要素を追加して、次のように構成します。

    • ブラウザのタイトル バーは、"Expenselt" です。

    • ブラウザの幅は 550 デバイス非依存ピクセルです。

    • ブラウザの高さは 350 ピクセルでデバイスに依存しません。

    • ページのタイトルは、"ExpenseIt - Home" です。

    この XAML マークアップは、次のようになります。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.HomePage"
      WindowTitle="ExpenseIt"
      Title="ExpenseIt - Home" 
      WindowWidth="550" WindowHeight="380">
    </Page>
    
  3. HomePage.xaml.cs という新しいコードを作成します。このファイルは、HomePage.xaml で宣言されたイベントを処理するコードを含む分離コード ファイルになります。コードは、次のようになります。

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    namespace ExpenseIt
    {
        public partial class HomePage : Page
        {
            public HomePage()
            {
                InitializeComponent();
            }
        }
    }
    
  4. ExpenseReportPage.xaml という新しい XAML マークアップ ファイルを作成します。Page 要素を追加し、そのページ タイトルを "ExpenseIt - View Expense Report" に設定します。このページには、HomePage.xaml で選択された個人の経費報告書が表示されます。この XAML マークアップは、次のようになります。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.ExpenseReportPage"
      Title="ExpenseIt - View Expense Report">
    </Page>
    
  5. ExpenseReportPage.xaml.cs という新しいファイルを作成します。このファイルは、ExpenseReportPage.xaml で定義された UI に経費報告書データをバインドする分離コード ファイルになります。コードは、次のようになります。

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    namespace ExpenseIt
    {
        public partial class ExpenseReportPage : Page
        {
            public ExpenseReportPage()
            {
                InitializeComponent();
            }
        }
    }
    
  6. watermark.png という名前のイメージを、前の手順で作成した 5 つのコード ファイルと同じフォルダに追加します。独自のイメージを作成することも、サンプル コードから同じ名前のファイルをコピーすることもできます。

アプリケーションのビルドと実行

この手順では、MSBuild を使用して、前のセクションで定義したアプリケーションをビルドします。

  1. ExpenseIt.csproj という新しいファイルを作成します。このファイルは、MSBuild ファイルという特別な XML ファイルになります。ここには、アプリケーションのビルド構成と次のような内容が含まれます。

    • コンパイルされるプロジェクトのグローバル ビルド変数。これには、ビルド アセンブリの名前、ビルドするアセンブリの種類、ビルドされたアセンブリの追加先フォルダなどが含まれます。

    • コード ファイルへの参照

    • アプリケーションが使用する型を含む Microsoft .NET Framework アセンブリへの参照

    ビルド ファイルの内容は次のようになります。

    <?xml version="1.0" encoding="utf-8"?>
    <Project xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
        <PropertyGroup>
            <AssemblyName>ExpenseIt</AssemblyName>
            <TargetType>winexe</TargetType>
            <OutputPath>bin\$(Configuration)\</OutputPath>
        </PropertyGroup>
        <ItemGroup>
            <Reference Include="System"/>
            <Reference Include="System.Xml"/>
            <Reference Include="System.Data"/>
            <Reference Include="WindowsBase"/>
            <Reference Include="PresentationCore"/>
            <Reference Include="PresentationFramework"/>
        </ItemGroup>
        <ItemGroup>
            <ApplicationDefinition Include="App.xaml"/>
            <Page Include="HomePage.xaml"/>
            <Compile Include="HomePage.xaml.cs" />
            <Page Include="ExpenseReportPage.xaml"/>
            <Compile Include="ExpenseReportPage.xaml.cs" />
            <Resource Include="watermark.png"/>
        </ItemGroup>
        <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets"/>
        <Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets"/>
    </Project>
    
  2. プロジェクト ファイルやアプリケーション コード ファイルと同じフォルダでコマンド ウィンドウを開きます。

  3. コマンド プロンプトで、次のコマンドを実行します。

    MSBuild ExpenseIt.csproj

    Microsoft Visual Basic .NET の場合は、代わりに次のコマンドを実行します。

    MSBuild ExpenseIt.vbproj

    Visual Studio を使用してアプリケーションをコンパイルおよび実行するには、Visual Studio でプロジェクト ファイルを開き、F5 キーを押します。

ms752299.alert_note(ja-jp,VS.90).gifメモ :

Visual Studio 2005 によって、プロジェクト ファイルは自動的に生成されます。このチュートリアルでは、Visual Studio がインストールされていることが前提になっていないため、プロジェクト ファイルを作成するためのプロセスが細かくなります。.csproj ファイルの詳細については、「WPF アプリケーション (WPF) のビルド」を参照してください。Visual Studio を使用してこのチュートリアルを実行する場合は、生成された .csproj ファイルの内容を前の MSBuild テキストで上書きします。

  1. ビルドされたアプリケーションの実行可能ファイル expenseit.exe を含むフォルダを開きます。コマンド プロンプトからビルドした場合、expenseit.exe は次のフォルダにあります。

    アプリケーション コード ファイルを含むフォルダ\bin\

    Visual Studio を使用してビルドした場合、expenseit.exe は次のフォルダにあります。

    アプリケーション コード ファイルを含むフォルダ\bin\debug\

  2. コマンド プロンプトから、expenseit.exe を実行します。次の図は、実行中のアプリケーションを示しています。

    ExpenseIt のサンプルのスクリーン ショット

レイアウトの追加

レイアウトは、UI 要素の配置を整えるほか、UI のサイズが変更された場合に各要素のサイズと位置を管理します。通常、UI にレイアウトを追加するには、次のレイアウト コントロールのいずれかを使用します。

これらの各コントロールは、その子要素に対して特別な種類のレイアウトをサポートします。ExpenseIt のページはサイズの変更が可能で、各ページの要素は縦にも横にも他の要素と揃えられています。したがって、このアプリケーションにとっては Grid が最適なレイアウト要素です。

ms752299.alert_note(ja-jp,VS.90).gifメモ :

Panel 要素の詳細については、「パネルの概要」を参照してください。

次の XAML マークアップは、Grid を HomePage.xaml に追加して、10 ピクセルのマージンを持つ 3 行 1 列のテーブルを作成します。

  1. HomePage.xaml を開きます。

  2. Page タグ間に XAML を追加します。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.HomePage"
      WindowTitle="ExpenseIt"
      Title="ExpenseIt - Home" 
      WindowWidth="550" WindowHeight="380">
        <Grid Margin="10">
          <Grid.ColumnDefinitions>
            <ColumnDefinition />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition Height="Auto" />
          </Grid.RowDefinitions>
        </Grid>
    </Page>
    

コントロールの追加

この手順では、ホーム ページの UI を更新して個人の一覧を表示します。ユーザーは、この一覧から選択して、特定の個人の経費報告書を表示できます。この UI を作成するために、HomePage.xaml に次の要素を追加します。

  • ListBox (個人の一覧を表示します)。

  • Label (一覧のヘッダーとして使用します)。

  • Button (クリック時に、一覧で選択された個人の経費報告書を表示します)。

HomePage.xaml を更新するには、次の手順を使用します。

  1. HomePage.xaml ファイルの内容を次の XAML で上書きします。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.HomePage"
      WindowTitle="ExpenseIt"
      Title="ExpenseIt - Home" 
      WindowWidth="550" WindowHeight="380">
    
      <Grid Margin="10">
    
        <Grid.ColumnDefinitions>
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition />
          <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
    
        <!-- People list -->
        <Border Grid.Column="0" Grid.Row="0" Height="35" Padding="5" Background="#4E87D4">
          <Label VerticalAlignment="Center" Foreground="White">Names</Label>
        </Border>
        <ListBox Name="peopleListBox" Grid.Column="0" Grid.Row="1">
          <ListBoxItem>Mike</ListBoxItem>
          <ListBoxItem>Lisa</ListBoxItem>
          <ListBoxItem>John</ListBoxItem>
          <ListBoxItem>Mary</ListBoxItem>
        </ListBox>
    
        <!-- View report button -->
        <Button Grid.Column="0" Grid.Row="2" Margin="0,10,0,0" Width="125"
          Height="25" HorizontalAlignment="Right">View</Button>
    
      </Grid>
    
    </Page>
    
  2. アプリケーションをコンパイルして実行します。

この手順のコードで作成されたコントロールを次の図に示します。

ExpenseIt のサンプルのスクリーン ショット

イメージとタイトルの追加

この手順では、ホーム ページの UI を更新して、適切なイメージとページ タイトルを表示します。

  1. HomePage.xaml を開きます。

  2. HomePage.xaml ファイルの内容を次の XAML で上書きします。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.HomePage"
      WindowTitle="ExpenseIt"
      Title="ExpenseIt - Home" 
      WindowWidth="550" WindowHeight="380">
    
      <Grid>
    
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="230" />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition />
        </Grid.RowDefinitions>
    
        <DockPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0">
          <Canvas DockPanel.Dock="Left" Width="230" Height="100">
            <Image Source="watermark.png" />
          </Canvas>
          <Label VerticalAlignment="Center" FontFamily="Trebuchet MS" 
            FontWeight="Bold" FontSize="18" Foreground="#0066cc">
            View Expense Report
          </Label>
        </DockPanel>
    
        <Grid Margin="10" Grid.Column="1" Grid.Row="1">
    
          <Grid.ColumnDefinitions>
            <ColumnDefinition />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition Height="Auto" />
          </Grid.RowDefinitions>
    
          <!-- People list -->
          <Border Grid.Column="0" Grid.Row="0" Height="35" Padding="5" Background="#4E87D4">
            <Label VerticalAlignment="Center" Foreground="White">Names</Label>
          </Border>
          <ListBox Name="peopleListBox" Grid.Column="0" Grid.Row="1">
            <ListBoxItem>Mike</ListBoxItem>
            <ListBoxItem>Lisa</ListBoxItem>
            <ListBoxItem>John</ListBoxItem>
            <ListBoxItem>Mary</ListBoxItem>
          </ListBox>
    
          <!-- View report button -->
          <Button Grid.Column="0" Grid.Row="2" Margin="0,10,0,0" Width="125" 
            Height="25" HorizontalAlignment="Right">View</Button>
    
        </Grid>
    
      </Grid>
    </Page>
    

    この XAML は、次のように Grid を更新します。

    • 2 つの行を持つ新しいグリッドを作成します。

    • CanvasImage、および Label を含む DockPanel を最初の行に追加します。最初の行の 2 つの列を DockPanel で覆い、その左側に Canvas をドッキングすることで、LabelImage に重ねて表示できるようにします。

    • Image 要素の Source 属性を使用して、ソース イメージ watermark.png を指定します。

    • "View Expense Report" というタイトル テキストを Label に追加します。

    • Canvas および Label の属性を使用して、外観とサイズを構成します。

    • 既に HomePage.xaml に含まれていたグリッドを、新しいグリッドの 2 行目の 2 列目に追加します。

  3. アプリケーションをコンパイルして実行します。

この手順の結果を次の図に示します。

ExpenseIt のサンプルのスクリーン ショット

イベントを処理するコードの追加

  1. HomePage.xaml を開きます。

  2. 前の手順で定義した Button 要素を次のコードで上書きします。

    ...
    <!-- View report button -->
    <Button Grid.Column="0" Grid.Row="2" Width="125" Height="25" 
      Margin="0,10,0,0" HorizontalAlignment="Right" 
      Click="viewButton_Click">View</Button>
    ...
    
    ms752299.alert_note(ja-jp,VS.90).gifメモ :

    処理する Button イベントの名前は Click です。開発者が定義するイベント ハンドラの名前は、viewButton_Click になります。イベント ハンドラは、Button コントロールの Click イベントに登録されます。

  3. このチュートリアルの「アプリケーション コード ファイルの作成」の手順で作成した HomePage.xaml.cs を開きます。

  4. ファイルの内容を次のコードで上書きします。これにより、Click イベントを処理するコードが追加されます。このコードでは、ExpenseReportPage.xaml ファイルに移動します。

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    namespace ExpenseIt
    {
        public partial class HomePage : Page
        {
            public HomePage()
            {
                InitializeComponent();
            }
            private void viewButton_Click(object sender, RoutedEventArgs args)
            {
                // View Expense Report
                ExpenseReportPage expenseReportPage = new ExpenseReportPage();
                this.NavigationService.Navigate(expenseReportPage);
            }
        }
    }
    

ExpenseReportPage の UI の作成

ExpenseReportPage.xaml には、HomePage.xaml で選択した個人の経費報告書が表示されます。次の更新では、ExpenseReportPage.xaml の基本的な UI を作成するコントロールとレイアウトを追加します。また、さまざまな UI 要素の背景と塗りつぶしの色も追加します。

  1. ExpenseReportPage.xaml ファイルを開き、次のコードを追加します。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.ExpenseReportPage"
      Title="ExpenseIt - View Expense Report">
    
      <Grid>
    
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="230" />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition />
        </Grid.RowDefinitions>
    
        <DockPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0">
          <Canvas DockPanel.Dock="Left" Width="230" Height="100">
            <Image Source="watermark.png" />
          </Canvas>
          <Label VerticalAlignment="Center" FontFamily="Trebuchet MS" 
            FontWeight="Bold" FontSize="18" Foreground="#0066cc">
            Expense Report For:
          </Label>
        </DockPanel>
    
        <Grid Margin="10" Grid.Column="1" Grid.Row="1">
    
          <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition />
          </Grid.RowDefinitions>
    
          <!-- Name -->
          <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal">
            <Label Margin="0,0,0,5" FontWeight="Bold">Name:</Label>
            <Label Margin="0,0,0,5" FontWeight="Bold"></Label>
          </StackPanel>
    
          <!-- Department -->
          <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" 
            Orientation="Horizontal">
            <Label Margin="0,0,0,5" FontWeight="Bold">Department:</Label>
            <Label Margin="0,0,0,5" FontWeight="Bold"></Label>
          </StackPanel>
    
          <Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="3">
    
            <Grid.ColumnDefinitions>
              <ColumnDefinition />
              <ColumnDefinition Width="10" />
              <ColumnDefinition />
            </Grid.ColumnDefinitions>
    
            <Grid.RowDefinitions>
              <RowDefinition Height="Auto" />
              <RowDefinition />
            </Grid.RowDefinitions>
    
            <!-- Expense type list -->
            <Border Grid.Column="0" Grid.Row="0" Height="35" Padding="5" Background="#4E87D4">
              <Label VerticalAlignment="Center" Foreground="White">Expense Type</Label>
            </Border>
            <ListBox Grid.Column="0" Grid.Row="1" />
    
            <!-- Amount list -->
            <Border Grid.Column="2" Grid.Row="0" Height="35" Padding="5" Background="#4E87D4">
              <Label VerticalAlignment="Center" Foreground="White">Amount</Label>
            </Border>
            <ListBox Grid.Column="2" Grid.Row="1" />
    
          </Grid>
        </Grid>
      </Grid>
    </Page>
    
  2. アプリケーションをコンパイルして実行します。

ExpenseReportPage.xaml に追加された UI 要素を次の図に示します。

ExpenseIt のサンプルのスクリーン ショット

コントロールにスタイルを適用するコードの追加

多くの場合、UI では、要素の種類が同じであれば、外観もすべて同じになります。UI では、複数の要素間で外観を再利用できるように、スタイルが使用されます。スタイルの再利用性により、XAML マークアップの作成と管理が簡略化されます。この手順では、これまでの手順で定義した要素ごとの属性をスタイルに置き換えます。

  1. このチュートリアルの「アプリケーション コード ファイルの作成」の手順で作成した App.xaml を開きます。

  2. ファイルの内容を次の XAML マークアップで上書きします。

    <Application 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      StartupUri="HomePage.xaml">
    
      <Application.Resources>
    
        <!-- Background image style -->
        <Style x:Key="backgroundImageStyle">
          <Setter Property="Image.Source" Value="watermark.png"/>
        </Style>
    
        <!-- Header text style -->
        <Style x:Key="headerTextStyle">
          <Setter Property="Label.VerticalAlignment" Value="Center"></Setter>
          <Setter Property="Label.FontFamily" Value="Trebuchet MS"></Setter>
          <Setter Property="Label.FontWeight" Value="Bold"></Setter>
          <Setter Property="Label.FontSize" Value="18"></Setter>
          <Setter Property="Label.Foreground" Value="#0066cc"></Setter>
        </Style>
    
        <!-- Label style -->
        <Style x:Key="labelStyle" TargetType="{x:Type Label}">
          <Setter Property="VerticalAlignment" Value="Top" />
          <Setter Property="HorizontalAlignment" Value="Left" />
          <Setter Property="FontWeight" Value="Bold" />
          <Setter Property="Margin" Value="0,0,0,5" />
        </Style>
    
        <!-- List header style -->
        <Style x:Key="listHeaderStyle" TargetType="{x:Type Border}">
          <Setter Property="Height" Value="35" />
          <Setter Property="Padding" Value="5" />
          <Setter Property="Background" Value="#4E87D4" />
        </Style>
    
        <!-- List header text style -->
        <Style x:Key="listHeaderTextStyle" TargetType="{x:Type Label}">
          <Setter Property="Foreground" Value="White" />
          <Setter Property="VerticalAlignment" Value="Center" />
          <Setter Property="HorizontalAlignment" Value="Left" />
        </Style>
    
        <!-- Button style -->
        <Style x:Key="buttonStyle" TargetType="{x:Type Button}">
          <Setter Property="Width" Value="125" />
          <Setter Property="Height" Value="25" />
          <Setter Property="Margin" Value="0,10,0,0" />
          <Setter Property="HorizontalAlignment" Value="Right" />
        </Style>
    
      </Application.Resources>
    
    </Application>
    

    この XAML マークアップは、次のスタイルを追加します。

    • headerTextStyle: ページ タイトルの Label を書式設定します。

    • labelStyle: Label ラベルを書式設定します。

    • listHeaderStyle: 一覧のヘッダーの Border コントロールを書式設定します。

    • listHeaderTextStyle: 一覧のヘッダーの Label を書式設定します。

    • buttonStyle: HomePage.xaml のボタンを書式設定します。

    スタイルは、Application.Resources プロパティ要素の子であるリソースです。ここでは、スタイルはアプリケーション内のすべての要素に適用されます。.NET Framework アプリケーションでリソースを使用する例については、「方法 : アプリケーション リソースを使用する」を参照してください。

  3. HomePage.xaml を開きます。

  4. ファイルの内容を次のコードで上書きします。この手順では、各要素の外観固有の属性を適切なスタイルで置き換えます。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.HomePage"
      WindowTitle="ExpenseIt"
      Title="ExpenseIt - Home" 
      WindowWidth="550" WindowHeight="380">
    
      <Grid>
    
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="230" />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition />
        </Grid.RowDefinitions>
    
        <DockPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0">
          <Canvas DockPanel.Dock="Left" Width="230" Height="100">
            <Image Style="{StaticResource backgroundImageStyle}" />
          </Canvas>
          <Label Style="{StaticResource headerTextStyle}">View Expense Report</Label>
        </DockPanel>
    
        <Grid Margin="10" Grid.Column="1" Grid.Row="1">
    
          <Grid.ColumnDefinitions>
            <ColumnDefinition />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition Height="Auto" />
          </Grid.RowDefinitions>
    
          <!-- People list -->
          <Border Grid.Column="0" Grid.Row="0" Style="{StaticResource listHeaderStyle}">
            <Label Style="{StaticResource listHeaderTextStyle}">Names</Label>
          </Border>
          <ListBox Name="peopleListBox" Grid.Column="0" Grid.Row="1">
            <ListBoxItem>Mike</ListBoxItem>
            <ListBoxItem>Lisa</ListBoxItem>
            <ListBoxItem>John</ListBoxItem>
            <ListBoxItem>Mary</ListBoxItem>
          </ListBox>
    
          <!-- View report button -->
          <Button Grid.Column="0" Grid.Row="2" Style="{StaticResource buttonStyle}" 
            Click="viewButton_Click">View
          </Button>
    
        </Grid>
    
      </Grid>
    
    </Page>
    
  5. ExpenseReportPage.xaml を開きます。

  6. ファイルの内容を次のコードで上書きします。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.ExpenseReportPage"
      Title="ExpenseIt - View Expense Report">
    
      <Grid>
    
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="230" />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition />
        </Grid.RowDefinitions>
    
        <DockPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0">
          <Canvas DockPanel.Dock="Left" Width="230" Height="100">
            <Image Style="{StaticResource backgroundImageStyle}" />
          </Canvas>
          <Label Style="{StaticResource headerTextStyle}">Expense Report For:</Label>
        </DockPanel>
    
        <Grid Margin="10" Grid.Column="1" Grid.Row="1">
    
          <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition />
          </Grid.RowDefinitions>
    
          <!-- Name -->
          <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal">
            <Label Style="{StaticResource labelStyle}">Name:</Label>
            <Label Style="{StaticResource labelStyle}"></Label>
          </StackPanel>
    
          <!-- Department -->
          <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal">
            <Label Style="{StaticResource labelStyle}">Department:</Label>
            <Label Style="{StaticResource labelStyle}"></Label>
          </StackPanel>
    
          <Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="3">
    
            <Grid.ColumnDefinitions>
              <ColumnDefinition />
              <ColumnDefinition Width="10" />
              <ColumnDefinition />
            </Grid.ColumnDefinitions>
    
            <Grid.RowDefinitions>
              <RowDefinition Height="Auto" />
              <RowDefinition />
            </Grid.RowDefinitions>
    
            <!-- Expense type list -->
            <Border Grid.Column="0" Grid.Row="0" Style="{StaticResource listHeaderStyle}">
              <Label Style="{StaticResource listHeaderTextStyle}">Expense Type</Label>
            </Border>
            <ListBox Grid.Column="0" Grid.Row="1" />
    
            <!-- Amount list -->
            <Border Grid.Column="2" Grid.Row="0" Style="{StaticResource listHeaderStyle}">
              <Label Style="{StaticResource listHeaderTextStyle}">Amount</Label>
            </Border>
            <ListBox Grid.Column="2" Grid.Row="1" />
    
          </Grid>
    
        </Grid>
    
      </Grid>
    
    </Page>
    
  7. アプリケーションをコンパイルして実行します。この手順で XAML マークアップを追加した後も、アプリケーションの外観はスタイルによる更新の前と変わりません。

コントロールへのデータのバインド

この手順では、さまざまなコントロールにバインドされる XML データを作成します。

  1. HomePage.xaml を開きます。

  2. ファイルの内容を次の XAML マークアップで上書きします。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.HomePage"
      WindowTitle="ExpenseIt"
      Title="ExpenseIt - Home" 
      WindowWidth="550" WindowHeight="380">
    
      <Grid>
    
        <Grid.Resources>
    
          <!-- Expense Report Data -->
          <XmlDataProvider x:Key="ExpenseDataSource" XPath="Expenses">
            <x:XData>
              <Expenses >
                <Person Name="Mike" Department="Legal">
                  <Expense ExpenseType="Lunch" ExpenseAmount="50" />
                  <Expense ExpenseType="Transportation" ExpenseAmount="50" />
                </Person>
                <Person Name="Lisa" Department="Marketing">
                  <Expense ExpenseType="Document printing"
                      ExpenseAmount="50"/>
                  <Expense ExpenseType="Gift" ExpenseAmount="125" />
                </Person>
                <Person Name="John" Department="Engineering">
                  <Expense ExpenseType="Magazine subscription" 
                     ExpenseAmount="50"/>
                  <Expense ExpenseType="New machine" ExpenseAmount="600" />
                  <Expense ExpenseType="Software" ExpenseAmount="500" />
                </Person>
                <Person Name="Mary" Department="Finance">
                  <Expense ExpenseType="Dinner" ExpenseAmount="100" />
                </Person>
              </Expenses>
            </x:XData>
          </XmlDataProvider>
    
          <!-- Name item template -->
          <DataTemplate x:Key="nameItemTemplate">
            <Label Content="{Binding XPath=@Name}"/>
          </DataTemplate>
    
        </Grid.Resources>
    
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="230" />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition />
        </Grid.RowDefinitions>
    
        <DockPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0">
          <Canvas DockPanel.Dock="Left" Width="230" Height="100">
            <Image Style="{StaticResource backgroundImageStyle}" />
          </Canvas>
          <Label Style="{StaticResource headerTextStyle}">View Expense Report</Label>
        </DockPanel>
    
        <Grid Margin="10" Grid.Column="1" Grid.Row="1">
    
          <Grid.ColumnDefinitions>
            <ColumnDefinition />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition Height="Auto" />
          </Grid.RowDefinitions>
    
          <!-- People list -->
          <Border Grid.Column="0" Grid.Row="0" Style="{StaticResource listHeaderStyle}">
            <Label Style="{StaticResource listHeaderTextStyle}">Names</Label>
          </Border>
          <ListBox Name="peopleListBox" Grid.Column="0" Grid.Row="1" 
            ItemsSource="{Binding Source={StaticResource ExpenseDataSource}, XPath=Person}" 
            ItemTemplate="{StaticResource nameItemTemplate}" />
    
          <!-- View report button -->
          <Button Grid.Column="0" Grid.Row="2" Style="{StaticResource buttonStyle}" 
            Click="viewButton_Click">View</Button>
    
        </Grid>
    
      </Grid>
    
    </Page>
    

    データは Grid リソースとして作成されます。

コントロールへのデータの接続

この手順では、HomePage 上の個人の一覧で選択されている現在の項目を取得し、その参照を ExpenseReportPage のコンストラクタに渡してインスタンス化するコードを作成します。ExpenseReportPage は、渡された項目を使用してデータ コンテキストを設定します。この項目が、ExpenseReportPage.xaml で定義されたコントロールのバインド先となります。

  1. HomePage.xaml.cs を開きます。

  2. ファイルの内容を次のコードで上書きします。

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    namespace ExpenseIt
    {
        public partial class HomePage : Page
        {
            public HomePage()
            {
                InitializeComponent();
            }
    
            private void viewButton_Click(object sender, RoutedEventArgs args)
            {
                // Create a new expense report page and pass it the selected person
                // by using the non-default constructor.
                ExpenseReportPage expenseReportPage = 
                    new ExpenseReportPage(this.peopleListBox.SelectedItem);
    
                // Navigate to the expense report page,
                this.NavigationService.Navigate(expenseReportPage);
            }
        }
    }
    
  3. ExpenseReportPage.xaml.cs を開きます。

  4. ファイルの内容を次のコードで上書きします。

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    namespace ExpenseIt
    {
        public partial class ExpenseReportPage : Page
        {
            public ExpenseReportPage(object data)
            {
                InitializeComponent();
    
                // Bind to expense report data.
                this.DataContext = data;
            }
        }
    }
    

データ テンプレートを使用したデータへのスタイルの追加

この手順では、データ テンプレートを使用して、データ バインド リスト内の各項目の UI を更新します。

  1. ExpenseReportPage.xaml を開きます。

  2. ファイルの内容を次のコードで上書きします。

    <Page 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="ExpenseIt.ExpenseReportPage"
      Title="ExpenseIt - View Expense Report">
    
      <Grid>
    
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="230" />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition />
        </Grid.RowDefinitions>
    
        <DockPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0">
          <Canvas DockPanel.Dock="Left" Width="230" Height="100">
            <Image Style="{StaticResource backgroundImageStyle}" />
          </Canvas>
          <Label Style="{StaticResource headerTextStyle}">Expense Report For:</Label>
        </DockPanel>
    
        <Grid Margin="10" Grid.Column="1" Grid.Row="1">
    
          <Grid.Resources>
            <!-- Reason item template -->
            <DataTemplate x:Key="typeItemTemplate">
              <Label Content="{Binding XPath=@ExpenseType}"/>
            </DataTemplate>
            <!-- Amount item template -->
            <DataTemplate x:Key="amountItemTemplate">
              <Label Content="{Binding XPath=@ExpenseAmount}"/>
            </DataTemplate>
          </Grid.Resources>
    
          <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition />
          </Grid.RowDefinitions>
    
          <!-- Name -->
          <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal">
            <Label Style="{StaticResource labelStyle}">Name:</Label>
            <Label Content="{Binding XPath=@Name}" Style="{StaticResource labelStyle}"/>
          </StackPanel>
    
          <!-- Department -->
          <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal">
            <Label Style="{StaticResource labelStyle}">Department:</Label>
            <Label Content="{Binding XPath=@Department}" Style="{StaticResource labelStyle}"/>
          </StackPanel>
          <Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="3">
    
            <Grid.ColumnDefinitions>
              <ColumnDefinition />
              <ColumnDefinition Width="10" />
              <ColumnDefinition />
            </Grid.ColumnDefinitions>
    
            <Grid.RowDefinitions>
              <RowDefinition Height="Auto" />
              <RowDefinition />
            </Grid.RowDefinitions>
    
            <!-- Expense type list -->
            <Border Grid.Column="0" Grid.Row="0" Style="{StaticResource listHeaderStyle}">
              <Label Style="{StaticResource listHeaderTextStyle}">Expense Type</Label>
            </Border>
            <ListBox Grid.Column="0" Grid.Row="1" ItemsSource="{Binding XPath=Expense}" 
              ItemTemplate="{StaticResource typeItemTemplate}" />
    
            <!-- Amount list -->
            <Border Grid.Column="2" Grid.Row="0" Style="{StaticResource listHeaderStyle}">
              <Label Style="{StaticResource listHeaderTextStyle}">Amount</Label>
            </Border>
            <ListBox Grid.Column="2" Grid.Row="1" ItemsSource="{Binding XPath=Expense}" 
              ItemTemplate="{StaticResource amountItemTemplate}" />
    
          </Grid>
    
        </Grid>
    
      </Grid>
    
    </Page>
    
  3. アプリケーションをコンパイルして実行します。

データ テンプレートは、Grid リソースとして定義されます。

次の 2 つの図は、コントロール、レイアウト、スタイル、データ バインディング、およびデータ テンプレートが適用された ExpenseIt アプリケーションの両方のページを示しています。

ExpenseIt のサンプルのスクリーン ショット

最適な使用方法

このサンプルでは、Windows Presentation Foundation の特定の機能を紹介しています。そのため、アプリケーション開発のベスト プラクティスには従っていません。Windows Presentation Foundation (WPF) および Microsoft .NET Framework でのアプリケーション開発のベスト プラクティスに関する包括的な説明については、必要に応じて次のトピックを参照してください。

ユーザー補助 - 「ユーザー補助のベスト プラクティス

セキュリティ - 「Windows Presentation Foundation のセキュリティ

ローカリゼーション - 「WPF のグローバリゼーションおよびローカリゼーションの概要

WPF アプリケーションのパフォーマンスの最適化

次の内容

ここでは、Windows Presentation Foundation (WPF) を使用して UI を自由に作成する多くの方法を学習しました。データ バインドされた .NET Framework アプリケーションの基本的なビルド ブロックについて幅広く説明してきました。このトピックですべてを網羅したわけではありませんが、このトピックに示した方法以外にも独自の方法を発見できる可能性があります。

パネルの詳細については、「パネルの概要」を参照してください。データ テンプレートの詳細については、「データ テンプレートの概要」を参照してください。

参照

概念

レイアウト システム

パネルの概要

データ バインディングの概要

データ テンプレートの概要

WPF アプリケーション (WPF) のビルド