天天看點

WPF開發示例,詳細操作步驟 演練:開始使用 WPF

演練:開始使用 WPF

.NET Framework 4

其他版本

3(共 3)對本文的評價是有幫助 

- 評價此主題

更新: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#,并可在 

Introduction to Building WPF Applications

(生成

WPF 應用程式簡介)中找到。

系統必備元件

您需要以下元件來完成本演練:

  • Visual Studio 2010

有關安裝 Visual Studio 的更多資訊,請參見

安裝 Visual Studio

建立應用程式項目

在本節中,您将建立應用程式基礎結構,其中包括一個應用程式定義、兩個頁以及一個圖像。

  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。

    XAML 在 Visual Basic 中應如下所示:

    XAML
    <Application x:Class="Application"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="MainWindow.xaml">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    
    
          
    或者,在 C# 中應如下所示:
    <Application x:Class="ExpenseIt.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    
    
          
  3. 打開 MainWindow.xaml。

    此 XAML 檔案是應用程式的主視窗,并顯示在頁中建立的内容。 

    Window  類定義視窗的屬性(例如标題、大小或圖示)并處理事件(例如關閉或隐藏)。
  4. 将   元素更改為  NavigationWindow 此應用程式将導航到不同的内容,具體情況視使用者互動而定。 是以,需要将主   更改為   繼承 

     的所有屬性。 XAML

    檔案中的 

     元素建立   類的執行個體。 有關更多資訊,請參見 導航概述
  5. 更改   元素上的以下屬性:
    • Title  屬性設定為“ExpenseIt”。
    • Width  屬性設定為 500 像素。
    • Height  屬性設定為 350 像素。
    • 移除   标記之間的  Grid  元素。
    <NavigationWindow x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExpenseIt" Height="350" Width="500">
    
    </NavigationWindow>
    
    
          
    <NavigationWindow x:Class="ExpenseIt.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://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 類更改為從 

     中派生。

    在 Visual Basic 中,當您在 XAML 中更改視窗時,此操作将自動進行。

    您的代碼應如下所示。

    C# VB
    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();
            }
        }
    }
    
    
          
向應用程式中添加檔案

在本節中,将向應用程式中添加兩個頁和一個圖像。

  1. 向項目中添加一個名為 ExpenseItHome.xaml 的新頁 (WPF)。 有關更多資訊,請參見

    如何:向

    WPF 項目中添加新項

    此頁是應用程式啟動時顯示的第一頁。 它将顯示一個人員清單,使用者可從中選擇人員來顯示其零用金報帳單。
  2. 打開 ExpenseItHome.xaml。
  3.  設定為“ExpenseIt - Home”。
    <Page x:Class="ExpenseItHome"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="ExpenseIt - Home">
        <Grid>
    
        </Grid>
    </Page>
    
    
          
    <Page x:Class="ExpenseIt.ExpenseItHome"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
          mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300"
    	Title="ExpenseIt - Home">
    
        <Grid>
    
        </Grid>
    </Page>
    
    
          
  4.  上的  Source

     屬性設定為“ExpenseItHome.xaml”。

    這會将 ExpenseItHome.xaml 設定為應用程式啟動時打開的第一頁。 XAML 在 Visual Basic 中應如下所示:

    <NavigationWindow x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExpenseIt" Height="350" Width="500" Source="ExpenseItHome.xaml">
    
    </NavigationWindow>
    
    
          
    <NavigationWindow x:Class="ExpenseIt.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExpenseIt" Height="350" Width="500" Source="ExpenseItHome.xaml">
    
    </NavigationWindow>
    
    
          
  5. 向項目中添加一個名為 ExpenseReportPage.xaml 的新頁 (WPF)。

    此頁将顯示 ExpenseItHome.xaml 中所選人員的零用金報帳單。

  6. 打開 ExpenseReportPage.xaml。
  7.  設定為“ExpenseIt - View Expense”。
    <Page x:Class="ExpenseReportPage"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
          mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300"
          Title="ExpenseIt - View Expense">
        <Grid>
    
        </Grid>
    </Page>
    
    
          
    <Page x:Class="ExpenseIt.ExpenseReportPage"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
          mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300"
    	Title="ExpenseIt - View Expense">
    
        <Grid>
    
        </Grid>
    </Page>
    
    
          
  8. 打開 ExpenseItHome.xaml.vb 和 ExpenseReportPage.xaml.vb,或打開 ExpenseItHome.xaml.cs 和 ExpenseReportPage.xaml.cs。

    當您建立新的頁檔案時,Visual Studio 将自動建立代碼隐藏檔案。 這些代碼隐藏檔案處理用于響應使用者輸入的邏輯。

    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>publicpartialclass ExpenseItHome : Page
        {
            public ExpenseItHome()
            {
                InitializeComponent();
            }
        }
    }
    
    
          
    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>publicpartialclass ExpenseReportPage : Page
        {
            public ExpenseReportPage()
            {
                InitializeComponent();
            }
        }
    }
    
    
          
  9. 向項目中添加一個名為 watermark.png 的圖像。 可以建立自己的圖像,也可以從代碼示例中複制檔案。 有關更多資訊,請參見 如何:向項目添加現有項
生成和運作應用程式

在本節中,您将生成和運作應用程式。

  1. 通過按 F5 或從“調試”菜單中選擇“啟動調試”來生成和運作應用程式。

    下圖顯示帶有 

     按鈕的應用程式。
  2. 關閉應用程式以傳回到 Visual Studio。
建立布局

布局提供了放置 UI 元素的一種有序方法,并在 UI 調整大小時管理這些元素的大小和位置。 通常,将建立具有以下布局控件之一的布局:

其中每個布局控件都支援一種适用于其子元素的特殊布局類型。 ExpenseIt 頁面可以調整大小,并且每個頁面都具有沿其他元素水準和垂直排列的元素。 是以,

 是應用程式的理想布局元素。

有關  Panel  元素的更多資訊,請參見 面闆概述 。 有關布局的更多資訊,請參見 布局系統

在本節中,您将通過向 ExpenseItHome.xaml 中的 

 中添加列和行定義,來建立一個三行一列、邊距為 10 像素的表。

  1.  元素上的  Margin  屬性設定為“10,0,10,10”,對應于左邊距、上邊距、右邊距和下邊距。
  2. 在   标記之間添加以下 XAML 以建立行和列定義。 
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    
    
          
    兩個行的   設定為  Auto ,這意味着将根據行中的内容來調整行的大小。 預設   為  Star  大小調整,這意味着行将為可用空間的權重比例。 例如,如果兩個行的高度均為“*”,則它們各自的高度将為可用空間的一半。  現在應類似于以下 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

 附加屬性将每個控件放在 

 的一個行中。 有關附加屬性的更多資訊,請參見

附加屬性概述
  1.  标記之間添加以下 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>
    
    
          
  2. 生成并運作應用程式。

下圖顯示了在本節中通過 XAML 建立的控件。

添加圖像和标題

在本節中,首頁 UI 将更新為包含圖像和頁标題。

  1. 向  ColumnDefinitions  中添加強定 

     為

    230 像素的另一列。

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="230" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    
    
          
  2. RowDefinitions  中添加另一行。
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
        <RowDefinition />
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    
    
          
  3. 通過将  Grid.Column  設定為 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>
    
    
          
  4.  的  Background

     設定為

    watermark.png 圖像檔案。

    <Grid.Background>
        <ImageBrush ImageSource="watermark.png"/>
    </Grid.Background>
    
    
          
  5. Border  之前,添加一個 

    ,其中包含要作為頁标題的内容“View

    Expense Report”(檢視零用金報帳單)。

    <Label Grid.Column="1" VerticalAlignment="Center" FontFamily="Trebuchet MS" 
            FontWeight="Bold" FontSize="18" Foreground="#0066cc">
        View Expense Report
    </Label>
    
    
          

下圖顯示本節的結果。

添加代碼以處理事件
  1. 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>
    
    
          
  2. 打開 ExpenseItHome.xaml.vb 或 ExpenseItHome.xaml.cs。
  3.  事件處理程式中添加以下代碼,這些代碼使視窗導航到 ExpenseReportPage.xaml

    檔案。

    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. 此 UI 類似于在 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>
    
    
          
  2. 如果收到訓示   未找到或不存在的錯誤,請確定項目以 .NET Framework 4 為目标。 有關更多資訊,請參見

    如何:面向特定的

    .NET Framework 版本或配置檔案

  3. 單擊“View”(檢視)按鈕。

    零用金報帳單頁即會出現。

下圖顯示添加到 ExpenseReportPage.xaml 中的 UI 元素。 請注意,向後導航按鈕已啟用。

樣式控件

通常情況下,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:設定頁标題   的格式。
    • labelStyle:設定   控件的格式。
    • columnHeaderStyle:要進行格式設定的  DataGridColumnHeader
    • listHeaderStyle:設定清單标題 
    • listHeaderTextStyle:設定清單标題 
    • buttonStyle:設定 ExpenseItHome.xaml 上 
    請注意,樣式是 

     屬性元素的資源和子級。 這裡,樣式将應用于應用程式中的所有元素。 有關如何在

    .NET Framework 應用程式中使用資源的示例,請參見

    如何:使用應用程式資源
  3.  元素之間的所有内容替換為以下 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>
    
    
          
    通過應用樣式,将移除和替換定義每個控件的外觀的屬性,例如  VerticalAlignment  和  FontFamily

    。 例如,将 headerTextStyle 應用于“View

    Expense Report”(檢視零用金報帳單)

  4. <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>
    
    
          
    這将會向   元素中添加樣式。
  5. 在本節中添加 XAML 之後,應用程式看上去與使用樣式更新之前一樣。
将資料綁定到控件

在本節中,将建立綁定到各種控件的 XML 資料。

  1. 在起始   元素中,添加以下 XAML,以建立包含每個人員的資料的  XmlDataProvider 将以   資源的形式建立資料。 通常,此資料将以檔案形式加載,但為了簡單起見,将以内聯方式添加資料。
    <Grid.Resources>
    
    
    ...
    
    
    <!-- Expense Report Data -->
    <XmlDataProvider x:Key="ExpenseDataSource" XPath="Expenses">
        <x:XData>
            <Expenses xmlns="">
                <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>
    
    
          
  2.  資源中,添加以下  DataTemplate ,它定義如何在   中顯示資料。 有關資料模闆的更多資訊,請參見 資料模闆化概述
    <Grid.Resources>
    
    
    ...
    
    
    <!-- Name item template -->
    <DataTemplate x:Key="nameItemTemplate">
        <Label Content="{Binding XPath=@Name}"/>
    </DataTemplate>
    
    
    ...
    
    
    </Grid.Resources>
    
    
          
  3. 将現有   替換為以下 XAML。
    <ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2" 
             ItemsSource="{Binding Source={StaticResource ExpenseDataSource}, XPath=Person}"
             ItemTemplate="{StaticResource nameItemTemplate}">
    </ListBox>
    
    
          
    此 XAML 将  ItemsSource  屬性綁定到資料源,并應用資料模闆作為  ItemTemplate
将資料連接配接到控件

在本節中,您将編寫代碼來檢索在 ExpenseItHome.xaml 頁上的人員清單中標明的目前項,并在執行個體化過程中将對該目前項的引用傳遞給ExpenseReportPage 的構造函數。 ExpenseReportPage 使用已傳入的項設定資料上下文,這就是

ExpenseReportPage.xaml 中定義的控件要綁定的内容。

  1. 打開 ExpenseReportPage.xaml.vb 或 ExpenseReportPage.xaml.cs。
  2. 添加一個構造函數,該函數擷取一個對象,以便您能夠傳遞所選人員的零用金報帳單資料。
    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.  事件處理程式,以調用傳遞所選人員的零用金報帳單資料的新構造函數。
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // View Expense Report
        ExpenseReportPage expenseReportPage = new ExpenseReportPage(this.peopleListBox.SelectedItem);
        this.NavigationService.Navigate(expenseReportPage);
    
    }
    
    
          
使用資料模闆設定資料樣式

在本節中,您将使用資料模闆來更新資料綁定清單中各項的 UI。

  1. 将“Name”(名稱)和“Department”(部門) 元素的内容綁定到相應的資料源屬性。 有關資料綁定的更多資訊,請參見  資料綁定概述
    <!-- 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>
    
    
          
  2. 打開   元素後,添加以下資料模闆,這些資料模闆定義如何顯示零用金報帳單資料。
    <!--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>
    
    
          
  3. 将模闆應用于顯示零用金報帳單資料的   列。
    <!-- 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>
    
    
          
  4. 選擇一個人員,并單擊“View”(檢視)按鈕。

下圖顯示應用了控件、布局、樣式、資料綁定和資料模闆的 ExpenseIt 應用程式的兩個頁。