共用方式為


逐步解說:在 Windows Form 中裝載 Windows Presentation Foundation 複合控制項

更新:2007 年 11 月

本逐步解說會示範如何建立 WPF 複合控制項,並使用 ElementHost 控制項將它裝載 (Host) 於 Windows Form 控制項和表單中。

在本逐步解說中,您會實作包含兩個子控制項的 WPFUserControlUserControl 會顯示立體 (3-D) 圓錐體。由於使用 WPF 呈現立體物件要比使用 Windows Form 來呈現簡單的多,因此才會有在 Windows Form 中裝載 WPFUserControl 類別來建立立體圖形的這種做法。

逐步解說將說明的工作包括:

如需本逐步說明中所說明之工作的完整程式碼清單,請參閱在 Windows Form 中裝載 Windows Presentation Foundation 複合控制項範例

注意:根據您目前使用的設定或版本,您所看到的對話方塊與功能表命令可能會與 [說明] 中描述的不同。若要變更設定,請從 [工具] 功能表中選擇 [匯入和匯出設定]。如需詳細資訊,請參閱 Visual Studio 設定

必要條件

您需要下列元件才能完成此逐步解說:

  • Visual Studio 2008

建立使用者控制項

若要建立使用者控制項

  1. 建立 WPF 使用者控制項程式庫專案,並命名為 HostingWpfUserControlInWf。

  2. 在 WPF 設計工具中開啟 UserControl1.xaml。

  3. 將產生的程式碼取代成下列程式碼:

    這個程式碼會定義含有兩個子控制項的 System.Windows.Controls.UserControl。第一個子控制項是 System.Windows.Controls.Label 控制項,第二個則是會顯示立體圓錐體的 Viewport3D 控制項。

建立 Windows Form 主專案

若要建立主專案

  1. 將名稱為 WpfUserControlHost 的 Windows 應用程式專案加入至方案。如需詳細資訊,請參閱加入新的專案對話方塊

  2. 在 [方案總管中],加入名為 WindowsFormsIntegration.dll 之 WindowsFormsIntegration 組件的參考。

  3. 加入下列 WPF 組件的參考:

    • PresentationCore

    • PresentationFramework

    • WindowsBase

  4. 加入 HostingWpfUserControlInWf 專案的參考。

  5. 在 [方案總管] 中,設定要做為啟始專案的 WpfUserControlHost 專案。

裝載 Windows Presentation Foundation 使用者控制項

若要裝載使用者控制項

  1. 在 [Windows Form 設計工具] 中開啟 Form1。

  2. 在 [屬性] 視窗中按一下 [事件],然後按兩下 Load 事件以建立事件處理常式。

    [程式碼編輯器] 會開啟在新產生 Form1_Load 事件處理常式的地方。

  3. 將 Form1.cs 中的程式碼取代成下列程式碼。

    Form1_Load 事件處理常式會建立 UserControl1 執行個體,並將它加入至ElementHost 控制項的子控制項集合。而 ElementHost 控制項則會再加入至表單的子控制項集合。

    Imports System
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Data
    Imports System.Drawing
    Imports System.Text
    Imports System.Windows.Forms
    
    Imports System.Windows.Forms.Integration
    
    Public Class Form1
        Inherits Form
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            ' Create the ElementHost control for hosting the
            ' WPF UserControl.
            Dim host As New ElementHost()
            host.Dock = DockStyle.Fill
    
            ' Create the WPF UserControl.
            Dim uc As New HostingWpfUserControlInWf.UserControl1()
    
            ' Assign the WPF UserControl to the ElementHost control's
            ' Child property.
            host.Child = uc
    
            ' Add the ElementHost control to the form's
            ' collection of child controls.
            Me.Controls.Add(host)
        End Sub
    
    End Class
    
  4. 按 F5 建置並執行應用程式。

請參閱

工作

在 Windows Form 中裝載 Windows Presentation Foundation 複合控制項範例

概念

逐步解說:在 Windows Form 中裝載 Windows Presentation Foundation 控制項

逐步解說:在 Windows Presentation Foundation 中裝載 Windows Form 複合控制項

參考

ElementHost

WindowsFormsHost

其他資源

WPF 設計工具

移轉和互通性 HOW TO 主題