Share via


チュートリアル: WPF の概要

更新 : 2010 年 12 月

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

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

  • XAML を定義して、アプリケーションのuser interface (UI) の外観を設計します。

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

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

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

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

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

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

このチュートリアルの構築に使用するサンプル コードは、Microsoft Visual Basic と C# の両方が用意されています。WPF アプリケーションの構築の概要に関する記述を参照してください。

前提条件

このチュートリアルを実行するには、次のコンポーネントが必要です。

  • Visual Studio 2010

Visual Studio のインストールの詳細については、「Visual Studio のインストール」を参照してください。

アプリケーション プロジェクトの作成

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

  1. Visual Basic または Visual C# で ExpenseIt という名前の新しい WPF アプリケーション プロジェクトを作成します。 詳細については、「方法 : 新しい WPF アプリケーション プロジェクトを作成する」を参照してください。

    メモメモ

    このチュートリアルでは、.NET Framework 4 で使用できる DataGrid コントロールを使用します。プロジェクトで .NET Framework 4 を対象としてください。詳細については、「方法: 特定の .NET Framework のバージョンまたはプロファイルを対象として指定する」を参照してください。

  2. Application.xaml (Visual Basic) または App.xaml (C#) を開きます。

    この XAML ファイルでは、WPF アプリケーションとすべてのアプリケーション リソースを定義します。また、このファイルは、アプリケーションの起動時に自動的に表示する UI を指定するためにも使用されます。この例では、MainWindow.xaml を指定しています。

    Visual Basic では、XAML は次のようになります。

    <Application x:Class="Application"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="MainWindow.xaml">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    

    C# では、次のようになります。

    <Application x:Class="ExpenseIt.App"
         xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    
  3. MainWindow.xaml を開きます。

    この XAML ファイルは、アプリケーションのメイン ウィンドウであり、ページで作成されたコンテンツを表示します。 Window クラスは、ウィンドウのプロパティ (タイトル、サイズ、アイコンなど) を定義し、イベント (ウィンドウを閉じたり非表示にしたりするなど) を処理します。

  4. Window 要素を NavigationWindow に変更します。

    このアプリケーションでは、ユーザー操作に応じてさまざまなコンテンツに移動します。 そのため、メインの WindowNavigationWindow に変更する必要があります。 NavigationWindow は、Window のすべてのプロパティを継承します。 XAML ファイル内の NavigationWindow 要素は、NavigationWindow クラスのインスタンスを作成します。 詳細については、「ナビゲーションの概要」を参照してください。

  5. NavigationWindow 要素の次のプロパティを変更します。

    • Title プロパティを "ExpenseIt" に設定します。

    • Width プロパティを 500 ピクセルに設定します。

    • Height プロパティを 350 ピクセルに設定します。

    • NavigationWindow タグの間の Grid 要素を削除します。

    Visual Basic では、XAML は次のようになります。

    <NavigationWindow x:Class="MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExpenseIt" Height="350" Width="500">
    
    </NavigationWindow>
    

    C# では、次のようになります。

    <NavigationWindow x:Class="ExpenseIt.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExpenseIt" Height="350" Width="500">
    
    </NavigationWindow>
    
  6. MainWindow.xaml.vb または MainWindow.xaml.cs を開きます。

    このファイルは、MainWindow.xaml で宣言されたイベントを処理するコードを含む分離コード ファイルです。 このファイルには、XAML で定義されたウィンドウの部分クラスが含まれています。

  7. C# を使用している場合は、MainWindow クラスが NavigationWindow から派生するように変更します。

    Visual Basic では、XAML でウィンドウを変更すると自動的にこの処理が行われます。

    コードは、次のようになります。

    Class MainWindow
    
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace ExpenseIt
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : NavigationWindow
        {
            public MainWindow()
            {
                InitializeComponent();
            }
        }
    }
    

アプリケーションへのファイルの追加

このセクションでは、2 つのページと 1 つのイメージをアプリケーションに追加します。

  1. ExpenseItHome.xaml というプロジェクトに、新しいページ (WPF) を追加します。 詳細については、「方法 : 新しい項目を WPF プロジェクトに追加する」を参照してください。

    このページは、アプリケーションの起動時に最初に表示されるページです。 ここに個人の一覧が表示され、ユーザーは経費報告書の表示対象となる個人を選択できます。

  2. ExpenseItHome.xaml を開きます。

  3. Title を "ExpenseIt - Home" に設定します。

    Visual Basic では、XAML は次のようになります。

    <Page x:Class="ExpenseItHome"
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="https://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="ExpenseIt - Home">
        <Grid>
    
        </Grid>
    </Page>
    

    C# では、次のようになります。

    <Page x:Class="ExpenseIt.ExpenseItHome"
          xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="https://schemas.microsoft.com/expression/blend/2008" 
          mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300"
        Title="ExpenseIt - Home">
    
        <Grid>
    
        </Grid>
    </Page>
    
  4. MainWindow.xaml を開きます。

  5. NavigationWindowSource プロパティを "ExpenseItHome.xaml" に設定します。

    これにより、ExpenseItHome.xaml は、アプリケーションの起動時に最初に表示されるページに設定されます。 Visual Basic では、XAML は次のようになります。

    <NavigationWindow x:Class="MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExpenseIt" Height="350" Width="500" Source="ExpenseItHome.xaml">
    
    </NavigationWindow>
    

    C# では、次のようになります。

    <NavigationWindow x:Class="ExpenseIt.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExpenseIt" Height="350" Width="500" Source="ExpenseItHome.xaml">
    
    </NavigationWindow>
    
  6. ExpenseReportPage.xaml というプロジェクトに、新しいページ (WPF) を追加します。

    このページには、ExpenseItHome.xaml で選択された個人の経費報告書が表示されます。

  7. ExpenseReportPage.xaml を開きます。

  8. Title を "ExpenseIt - View Expense" に設定します。

    Visual Basic では、XAML は次のようになります。

    <Page x:Class="ExpenseReportPage"
          xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="https://schemas.microsoft.com/expression/blend/2008" 
          mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300"
          Title="ExpenseIt - View Expense">
        <Grid>
    
        </Grid>
    </Page>
    

    C# では、次のようになります。

    <Page x:Class="ExpenseIt.ExpenseReportPage"
          xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="https://schemas.microsoft.com/expression/blend/2008" 
          mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300"
        Title="ExpenseIt - View Expense">
    
        <Grid>
    
        </Grid>
    </Page>
    
  9. ExpenseItHome.xaml.vb と ExpenseReportPage.xaml.vb を開くか、または ExpenseItHome.xaml.cs と ExpenseReportPage.xaml.cs を開きます。

    新しいページ ファイルを作成すると、分離コード ファイルが自動的に作成されます。 これらの分離コード ファイルでは、ユーザー入力に応答するためのロジックを処理します。

    コードは、次のようになります。

    Class ExpenseItHome
    
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace ExpenseIt
    {
        /// <summary>
        /// Interaction logic for ExpenseItHome.xaml
        /// </summary>
        public partial class ExpenseItHome : Page
        {
            public ExpenseItHome()
            {
                InitializeComponent();
            }
        }
    }
    
    Class ExpenseReportPage
    
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace ExpenseIt
    {
        /// <summary>
        /// Interaction logic for ExpenseReportPage.xaml
        /// </summary>
        public partial class ExpenseReportPage : Page
        {
            public ExpenseReportPage()
            {
                InitializeComponent();
            }
        }
    }
    
  10. watermark.png という名前のイメージをプロジェクトに追加します。 独自のイメージを作成することも、サンプル コードからファイルをコピーすることもできます。 詳細については、「方法 : プロジェクトに既存の項目を追加する」を参照してください。

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

このセクションでは、アプリケーションをビルドして実行します。

  1. F5 キーを押すか、[デバッグ] メニューの [デバッグ開始] をクリックして、アプリケーションをビルドして実行します。

    次の図は、NavigationWindow ボタンのあるアプリケーションを示しています。

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

  2. アプリケーションを閉じて Visual Studio に戻ります。

レイアウトの作成

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

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

メモメモ

Panel 要素の詳細については、「パネルの概要」を参照してください。レイアウトの詳細については、「レイアウト システム」を参照してください。

このセクションでは、ExpenseItHome.xaml の Grid に列と行の定義を追加して、10 ピクセルのマージンを持つ 3 行 1 列のテーブルを作成します。

  1. ExpenseItHome.xaml を開きます。

  2. Grid 要素の Margin プロパティを "10,0,10,10" に設定します。"10,0,10,10" の各値は、左、上、右、下のマージンに対応しています。

  3. Grid タグの間に次の XAML を追加し、行と列の定義を作成します。 

    <Grid.ColumnDefinitions>
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    

    2 つの行の HeightAuto に設定されます。これは、行のサイズがその行に含まれるコンテンツに基づいて設定されることを意味します。 既定では、HeightStar サイズ値です。つまり、行は、使用可能なスペースの加重比率で示されます。 たとえば、2 つの行それぞれの高さが "*" の場合、各行の高さは、使用可能なスペースの半分です。

    Grid は、次の XAML のようになります。

    <Grid Margin="10,0,10,10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
    </Grid>
    

コントロールの追加

このセクションでは、ホーム ページの UI を更新して個人の一覧を表示します。ユーザーは、この一覧から選択して、特定の個人の経費報告書を表示できます。 コントロールとは、ユーザーがアプリケーションと対話できるようにする UI オブジェクトのことです。 詳細については、「コントロール」を参照してください。

この UI を作成するために、ExpenseItHome.xaml に次の要素を追加します。

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

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

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

各コントロールは、Grid.Row 添付プロパティを設定することで、Grid の行に配置されます。 添付プロパティの詳細については、「添付プロパティの概要」を参照してください。

  1. ExpenseItHome.xaml を開きます。

  2. Grid タグの間に次の XAML を追加します。

    
      <!-- 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>
    
  3. アプリケーションをビルドして実行します。

次の図は、このセクションの XAML で作成されたコントロールを示しています。

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

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

このセクションでは、ホーム ページの UI を更新して、イメージとページ タイトルを表示します。

  1. ExpenseItHome.xaml を開きます。

  2. ColumnDefinitions に、Width が 230 ピクセルで固定された新しい列を追加します。

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="230" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    
  3. RowDefinitions に新しい行を追加します。

    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
        <RowDefinition />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    
  4. Grid.Column を 1 に設定して、コントロールを 2 列目に移動します。 Grid.Row を 1 増加して、各コントロールを 1 行下へ移動します。

      <Border Grid.Column="1" Grid.Row="1" Height="35" Padding="5" Background="#4E87D4">
          <Label VerticalAlignment="Center" Foreground="White">Names</Label>
      </Border>
      <ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2">
          <ListBoxItem>Mike</ListBoxItem>
          <ListBoxItem>Lisa</ListBoxItem>
          <ListBoxItem>John</ListBoxItem>
          <ListBoxItem>Mary</ListBoxItem>
      </ListBox>
    
      <!-- View report button -->
      <Button Grid.Column="1" Grid.Row="3" Margin="0,10,0,0" Width="125"
    Height="25" HorizontalAlignment="Right">View</Button>
    
  5. GridBackground を watermark.png イメージ ファイルに設定します。

    <Grid.Background>
        <ImageBrush ImageSource="watermark.png"/>
    </Grid.Background>
    
  6. Border の前に、ページのタイトルになる "View Expense Report" というコンテンツが指定された Label を追加します。

    <Label Grid.Column="1" VerticalAlignment="Center" FontFamily="Trebuchet MS" 
            FontWeight="Bold" FontSize="18" Foreground="#0066cc">
        View Expense Report
    </Label>
    
  7. アプリケーションをビルドして実行します。

次の図は、このセクションの結果を示しています。

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

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

  1. ExpenseItHome.xaml を開きます。

  2. Button 要素に Click イベント ハンドラーを追加します。 詳細については、「方法 : 単純なイベント ハンドラーを作成する」を参照してください。

      <!-- View report button -->
      <Button Grid.Column="1" Grid.Row="3" Margin="0,10,0,0" Width="125"
    Height="25" HorizontalAlignment="Right" Click="Button_Click">View</Button>
    
  3. ExpenseItHome.xaml.vb または ExpenseItHome.xaml.cs を開きます。

  4. Click イベント ハンドラーに次のコードを追加します。これにより、ウィンドウが ExpenseReportPage.xaml ファイルに移動します。

            Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
                ' View Expense Report
                Dim expenseReportPage As New ExpenseReportPage()
                Me.NavigationService.Navigate(expenseReportPage)
    
            End Sub
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // View Expense Report
        ExpenseReportPage expenseReportPage = new ExpenseReportPage();
        this.NavigationService.Navigate(expenseReportPage);
    
    }
    

ExpenseReportPage の UI の作成

ExpenseReportPage.xaml には、ExpenseItHome.xaml で選択した個人の経費報告書が表示されます。 このセクションでは、コントロールを追加して、ExpenseReportPage.xaml の UI を作成します。 また、さまざまな UI 要素の背景と塗りつぶしの色も追加します。

  1. ExpenseReportPage.xaml を開きます。

  2. Grid タグの間に次の XAML を追加します。

    この UI は、DataGrid で表示されるレポート データ以外は、ExpenseItHome.xaml で作成した UI に似ています。

    <Grid.Background>
        <ImageBrush ImageSource="watermark.png" />
    </Grid.Background>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="230" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    
    
    <Label Grid.Column="1" VerticalAlignment="Center" FontFamily="Trebuchet MS" 
    FontWeight="Bold" FontSize="18" Foreground="#0066cc">
        Expense Report For:
    </Label>
    <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="2" VerticalAlignment="Top" 
              HorizontalAlignment="Left">
            <!-- Expense type and Amount table -->
            <DataGrid  AutoGenerateColumns="False" RowHeaderWidth="0" >
                <DataGrid.ColumnHeaderStyle>
                    <Style TargetType="{x:Type DataGridColumnHeader}">
                        <Setter Property="Height" Value="35" />
                        <Setter Property="Padding" Value="5" />
                        <Setter Property="Background" Value="#4E87D4" />
                        <Setter Property="Foreground" Value="White" />
                    </Style>
                </DataGrid.ColumnHeaderStyle>
                <DataGrid.Columns>
                    <DataGridTextColumn Header="ExpenseType" />
                    <DataGridTextColumn Header="Amount"  />
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Grid>
    
  3. アプリケーションをビルドして実行します。

    メモメモ

    DataGrid が見つからないか存在しないエラーが発生した場合は、プロジェクトで .NET Framework 4 を対象としてください。詳細については、「方法: 特定の .NET Framework のバージョンまたはプロファイルを対象として指定する」を参照してください。

  4. [View] をクリックします。

    経費報告書のページが表示されます。

ExpenseReportPage.xaml に追加された UI 要素を次の図に示します。 "戻る" ナビゲーション ボタンが有効になっていることに注意してください。

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

コントロールのスタイル設定

多くの場合、UI では、要素の種類が同じであれば、外観もすべて同じになります。 UI では、複数の要素間で外観を再利用できるように、スタイルが使用されます。 スタイルの再利用性により、XAML の作成と管理が簡略化されます。 スタイルの詳細については、「スタイルとテンプレート」を参照してください。 このセクションでは、これまでの手順で定義した要素ごとの属性をスタイルに置き換えます。

  1. Application.xaml または App.xaml を開きます。

  2. Application.Resources タグの間に次の XAML を追加します。

    
    <!-- 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>
    
    <!-- DataGrid header style -->
    <Style x:Key="columnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="Height" Value="35" />
        <Setter Property="Padding" Value="5" />
        <Setter Property="Background" Value="#4E87D4" />
        <Setter Property="Foreground" Value="White" />
    </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>
    

    この XAML では、次のスタイルが追加されます。

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

    • labelStyle: Label コントロールを書式設定します。

    • columnHeaderStyle: DataGridColumnHeader を書式設定します。

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

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

    • buttonStyle: ExpenseItHome.xaml の Button を書式設定します。

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

  3. ExpenseItHome.xaml を開きます。

  4. Grid 要素間のすべての内容を次の XAML に置き換えます。

    <Grid.Background>
        <ImageBrush ImageSource="watermark.png"  />
    </Grid.Background>
    
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="230" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
        <RowDefinition />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    
    <!-- People list -->
    
    <Label Grid.Column="1" Style="{StaticResource headerTextStyle}" >
        View Expense Report
    </Label>
    
    <Border Grid.Column="1" Grid.Row="1" Style="{StaticResource listHeaderStyle}">
        <Label Style="{StaticResource listHeaderTextStyle}">Names</Label>
    </Border>
    <ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2">
        <ListBoxItem>Mike</ListBoxItem>
        <ListBoxItem>Lisa</ListBoxItem>
        <ListBoxItem>John</ListBoxItem>
        <ListBoxItem>Mary</ListBoxItem>
    </ListBox>
    
    <!-- View report button -->
    <Button Grid.Column="1" Grid.Row="3" Click="Button_Click" Style="{StaticResource buttonStyle}">View</Button>
    

    各コントロールの外観を定義する VerticalAlignmentFontFamily などのプロパティは、スタイルを適用することにより、削除されて置き換えられます。 たとえば、headerTextStyle は、"View Expense Report" という Label に適用されます。

  5. ExpenseReportPage.xaml を開きます。

  6. Grid 要素間のすべての内容を次の XAML に置き換えます。

    <Grid.Background>
        <ImageBrush ImageSource="watermark.png" />
    </Grid.Background>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="230" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    
    
    <Label Grid.Column="1" Style="{StaticResource headerTextStyle}">
        Expense Report For:
    </Label>
    <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="2" VerticalAlignment="Top" 
              HorizontalAlignment="Left">
            <!-- Expense type and Amount table -->
            <DataGrid ColumnHeaderStyle="{StaticResource columnHeaderStyle}" 
                      AutoGenerateColumns="False" RowHeaderWidth="0" >
                <DataGrid.Columns>
                    <DataGridTextColumn Header="ExpenseType" />
                    <DataGridTextColumn Header="Amount"  />
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Grid>
    

    これにより、Label 要素と Border 要素にスタイルが追加されます。

  7. アプリケーションをビルドして実行します。

    このセクションで XAML を追加した後も、アプリケーションの外観はスタイルによる更新の前と変わりません。

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

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

  1. ExpenseItHome.xaml を開きます。

  2. 開始の Grid 要素の後に、各個人のデータを含む XmlDataProvider を作成する次の XAML を追加します。

    データは 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>
    
    
    ...
    
    
    </Grid.Resources>
    
  3. Grid リソースでは、次の DataTemplate を追加します。これにより、ListBox にデータを表示する方法が定義されます。 データ テンプレートの詳細については、「データ テンプレートの概要」を参照してください。

    <Grid.Resources>
    
    
    ...
    
    
    <!-- Name item template -->
    <DataTemplate x:Key="nameItemTemplate">
        <Label Content="{Binding XPath=@Name}"/>
    </DataTemplate>
    
    
    ...
    
    
    </Grid.Resources>
    
  4. 既存の ListBox を次の XAML に置き換えます。

    <ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2" 
             ItemsSource="{Binding Source={StaticResource ExpenseDataSource}, XPath=Person}"
             ItemTemplate="{StaticResource nameItemTemplate}">
    </ListBox>
    

    この XAML は、ListBoxItemsSource プロパティをデータ ソースにバインドし、データ テンプレートを ItemTemplate として適用します。

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

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

  1. ExpenseReportPage.xaml.vb または ExpenseReportPage.xaml.cs を開きます。

  2. オブジェクトを取得するコンストラクターを追加して、選択した個人の経費報告書データを渡せるようにします。

        Partial Public Class ExpenseReportPage
            Inherits Page
            Public Sub New()
                InitializeComponent()
            End Sub
    
            ' Custom constructor to pass expense report data
            Public Sub New(ByVal data As Object)
                Me.New()
                ' Bind to expense report data.
                Me.DataContext = data
            End Sub
    
        End Class
    
    public partial class ExpenseReportPage : Page
    {
        public ExpenseReportPage()
        {
            InitializeComponent();
        }
    
        // Custom constructor to pass expense report data
        public ExpenseReportPage(object data):this()
        {
            // Bind to expense report data.
            this.DataContext = data;
        }
    
    }
    
  3. ExpenseItHome.xaml.vb または ExpenseItHome.xaml.cs を開きます。

  4. 選択した個人の経費報告書データを渡す新しいコンストラクターを呼び出すように Click イベント ハンドラーを変更します。

            Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
                ' View Expense Report
                Dim expenseReportPage As New ExpenseReportPage(Me.peopleListBox.SelectedItem)
                Me.NavigationService.Navigate(expenseReportPage)
    
            End Sub
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // View Expense Report
        ExpenseReportPage expenseReportPage = new ExpenseReportPage(this.peopleListBox.SelectedItem);
        this.NavigationService.Navigate(expenseReportPage);
    
    }
    

データ テンプレートを使用したデータのスタイル設定

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

  1. ExpenseReportPage.xaml を開きます。

  2. "Name" および "Department" の Label 要素の内容を適切なデータ ソース プロパティにバインドします。 データ バインディングの詳細については、「データ バインディングの概要」を参照してください。

    <!-- Name -->
    <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal">
        <Label Style="{StaticResource labelStyle}">Name:</Label>
        <Label Style="{StaticResource labelStyle}" Content="{Binding XPath=@Name}"></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}" Content="{Binding XPath=@Department}"></Label>
    </StackPanel>
    
  3. Grid 要素を開いたら、経費報告書データの表示方法を定義する、次のデータ テンプレートを追加します。

    <!--Templates to display expense report data-->
    <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>
    
  4. 経費報告書データを表示する DataGrid 列にテンプレートを適用します。

    <!-- Expense type and Amount table -->
    <DataGrid ItemsSource="{Binding XPath=Expense}" ColumnHeaderStyle="{StaticResource columnHeaderStyle}" AutoGenerateColumns="False" RowHeaderWidth="0" >
    
        <DataGrid.Columns>
            <DataGridTextColumn Header="ExpenseType" Binding="{Binding XPath=@ExpenseType}"  />
            <DataGridTextColumn Header="Amount" Binding="{Binding XPath=@ExpenseAmount}" />
        </DataGrid.Columns>
    
    </DataGrid>
    
  5. アプリケーションをビルドして実行します。

  6. 個人を選択し、[View] をクリックします。

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

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

ベスト プラクティス

このサンプルでは、WPF の特定の機能を示します。そのため、アプリケーション開発のベスト プラクティスに従っていません。 WPF と .NET Framework のアプリケーション開発ベスト プラクティスの包括的な説明については、適宜、次のトピックを参照してください。

次の内容

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

WPF アーキテクチャおよびプログラミング モデルの詳細については、次のトピックを参照してください。

アプリケーションの作成の詳細については、次のトピックを参照してください。

参照

概念

パネルの概要

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

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

その他の技術情報

スタイルおよびテンプレート

履歴の変更

日付

履歴

理由

2010 年 12 月

.NET Framework 4 を対象とすることに関するメモを追加。

情報の拡充