Windows Presentation Foundation 使用者入門

更新:2007 年 11 月

本教學課程簡單的介紹 Windows Presentation Foundation (WPF) 應用程式的開發,包括大多數 WPF 應用程式都會用到的項目:可延伸標記語言 (XAML) 標記、程式碼後置 (Code-Behind)、應用程式定義、控制項、配置、資料繫結 (Data-Binding) 和樣式。

這個主題包含下列章節。

  • 摘要
  • 必要條件
  • 建立應用程式程式碼檔
  • 建置和執行應用程式
  • 加入配置
  • 加入控制項
  • 加入影像和標題
  • 加入處理事件的程式碼
  • 建立 ExpenseReportPage 的 UI
  • 加入設定控制項樣式的程式碼
  • 將資料繫結至控制項
  • 將資料連接到控制項
  • 使用資料範本將樣式加入至資料
  • 最佳作法
  • 下一步
  • 相關主題

摘要

本教學課程透過下列步驟帶領您逐步開發出一個簡單的 WPF 應用程式。

  • 定義 XAML 標記,以設計應用程式的使用者介面 (UI) 外觀。

  • 撰寫程式碼,以建置應用程式的行為。

  • 建立應用程式定義,以管理應用程式。

  • 加入控制項和配置,以組成應用程式 UI。

  • 建立樣式,以建立一致的應用程式 UI 外觀。

  • 將 UI 繫結至資料,使資料填入 UI,並使資料和 UI 保持同步。

當您完成本教學課程時,即建置好一支獨立的 Windows 應用程式,可以讓使用者檢視所選取人員的經費支出報表。應用程式將由數個 WPF 頁面組成,並裝載在類似瀏覽器的視窗中。

本教學課程中的程式碼範例另有 C# 和 Microsoft Visual Basic .NET 版,請參閱建置 Windows Presentation Foundation 應用程式簡介

必要條件

若要建置本教學課程中開發的應用程式,您的電腦必須安裝 Microsoft .NET Framework 和 Windows Software Development Kit (SDK)。

安裝這些軟體後,您就可以從命令視窗建置應用程式 (如果您想要,也可以用整合式開發環境 (IDE),如 Microsoft Visual Studio)。若要從命令提示字元建置,必須使用隨 Windows Software Development Kit (SDK) 一起安裝的命令視窗。您可以在下列功能表位置找到這個視窗:

  • [開始功能表] | [所有程式] | [Microsoft Windows SDK] | [CMD Shell]

或者,您也可以按照下列步驟開啟 Windows 命令提示字元:

  1. 選取 [開始] 功能表中的 [執行]。

  2. 請輸入下列:

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

  3. 按 [確定]。

請注意,SetEnv.cmd 會設定從命令提示字元建置 WPF 應用程式所需要的環境。

建立應用程式程式碼檔

在這個步驟建立的應用程式基礎結構,包括一個應用程式定義、兩個頁面和一個影像。

  1. 建立新的 XAML 標記檔案,取名為 App.xaml。這個檔案定義 WPF 應用程式,同時您也會用它指定要在應用程式啟動時自動顯示的 UI,即這個範例中的 HomePage.xaml (會在下一個步驟建立)。您的 XAML 標記應該像這樣:

    <Application 
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      StartupUri="HomePage.xaml">
    </Application>
    
  2. 建立新的 XAML 標記檔案,取名為 HomePage.xaml,它將是應用程式啟動時所顯示的第一個頁面。HomePage.xaml 會顯示一份人員清單,使用者可從中選取一名人員查看其經費支出報表。以下列組態將 Page 項目加入至 HomePage.xaml:

    • 瀏覽器的標題列是 "ExpenseIt"。

    • 瀏覽器的寬度是 550 與裝置無關 (Device-Independent) 的像素。

    • 瀏覽器的高度是 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。這個檔案是程式碼後置 (Code-Behind) 的檔案,其包含的程式碼要處理在 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. 建立新的 XAML 標記檔案,取名為 ExpenseReportPage.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。

注意事項:

Visual Studio 2005 會自動產生專案檔。因為本教學課程假定您沒有安裝 Visual Studio,所以會詳細說明建立專案檔的程序。如需建立 .csproj 檔案的詳細資訊,請參閱建置 WPF 應用程式 (WPF)。如果您是用 Visual Studio 來編譯本教學課程,請用前面的 MSBuild 文字覆寫產生的 .csproj 檔案內容。

  1. 開啟建置好的應用程式可執行檔 expenseit.exe 所在的資料夾。如果是從命令提示字元建置,則 expenseit.exe 位在下列資料夾中:

    Folder Containing Application Code Files\bin\

    如果是用 Visual Studio 建置,則 expenseit.exe 位在下列資料夾中:

    Folder Containing Application Code Files\bin\debug\

  2. 從命令提示字元執行 expenseit.exe。下圖顯示執行中的應用程式。

    ExpenseIt 範例螢幕擷取畫面

加入配置

配置提供一種有次序的放置 UI 項目的方式,並且管理調整 UI 大小時這些項目的大小和位置。您通常會以下列配置控制項將配置加入至您的 UI:

以上這些都支援一種用於其子項目的特殊配置類型。ExpenseIt 頁面的大小可以調整,各頁面都有項目會沿著其他項目水平和垂直排列。因此,Grid 是應用程式理想的配置項目。

注意事項:

如需 Panel 項目的詳細資訊,請參閱面板概觀

下列 XAML 標記會將 Grid 加入至 HomePage.xaml,建立含有一欄三列、邊界 10 個像素的表格:

  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. 以下列 XAML 覆寫 HomePage.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. 以下列 XAML 覆寫 HomePage.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

    • 建立含有兩列的新方格。

    • 在第一列中加入含有 CanvasImageLabelDockPanelDockPanel 橫跨第一列的兩欄,與停駐在左邊的 Canvas 一起會使 Label 重疊在 Image 之上。

    • Image 項目的 Source 屬性 (Attribute) 指定來源影像 watermark.png。

    • 將標題文字 "View Expense Report" 加入至 Label

    • CanvasLabel 的屬性 (Attribute) 設定它們的外觀和大小。

    • 將 HomePage.xaml 原本包含的方格移至新方格的第二列第二欄。

  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>
    ...
    
    注意事項:

    待處理的 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 標記的建立和管理。這個步驟會將先前步驟中定義的個別項目屬性 (Attribute) 取代為樣式:

  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 屬性 (Property) 項目的子系。在這裡,樣式會套用至應用程式中的所有項目。如需在 .NET Framework 應用程式中使用資源的範例,請參閱 HOW TO:使用應用程式資源

  3. 開啟 HomePage.xaml。

  4. 以下列程式碼覆寫這個檔案的內容。這個步驟會將各項目的外觀特定屬性 (Attribute) 取代為適當的樣式。

    <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 上的人員清單中選取的項目,並在執行個體化 (Instantiation) 期間將其參考傳遞至 ExpenseReportPage 的建構函式 (Constructor)。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 資源。

以下兩張圖中顯示 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)