共用方式為


逐步解說:在 WPF 應用程式中裝載協力廠商 Windows Form 控制項

本逐步解說示範如何使用 WPF Designer for Visual Studio,在 WPF 應用程式中裝載 Windows Form 協力廠商控制項。 如需 Windows Form 和 WPF 互通性的詳細資訊,請參閱移轉和互通性

在本逐步解說中,您將使用 MonthCalendar 控制項以代表協力廠商的控制項。 您要建立一個 UserControl 型別,其 Controls 集合中有一個 MonthCalendar 控制項的執行個體。 UserControl 型別會公開 Date 屬性,並實作自訂邏輯以定義 MonthCalendar 控制項的行為。 在 WPF 應用程式中,TextBlock 項目會繫結至 Date 屬性。

在這個逐步解說中,您會執行下列工作:

  • 建立 WPF 專案。

  • 建立 Windows Form 使用者控制項,以封裝廠商的控制項。

  • 在 WPF 應用程式中,裝載 Windows Form 使用者控制項。

下圖顯示應用程式的顯示方式。

裝載 Windows Form 控制項

注意

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

必要條件

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

  • Visual Studio 2012 RC.

建立 WPF 專案

第一步是建立主應用程式的 WPF 專案。

若要建立專案

  1. 在 Visual Basic 或 Visual C# 中,建立名為 HostingMonthCalendar 的新 WPF 應用程式專案。 如需詳細資訊,請參閱 HOW TO:建立新的 WPF 應用程式專案

    MainWindow.xaml 隨即在 WPF Designer中開啟。

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

建立 Windows Form 複合控制項

這個程序會顯示如何從 UserControl 類別衍生出型別,以建立複合控制項。

若要建立 Windows Form 複合控制項

  1. 在 Visual Basic 或 Visual C# 中,將名為 VendorControlLibrary 的新 Windows Form 控制項程式庫專案加入至方案。 如需詳細資訊,請參閱 How to: Add and Remove Solution Items

    UserControl1 隨即在 Windows Form 設計工具中開啟。

  2. 在 [方案總管] 中,以滑鼠右鍵按一下 UserControl1 檔案,然後選取 [重新命名]。

  3. 將控制項的名稱變更為 VendorControl。 當詢問您是否要重新命名所有參考時,請按一下 []。

  4. 在設計介面上,選取 VendorControl。

  5. 在 [屬性] 視窗中,將 Size 屬性值設定為 200,200。

  6. 從 [工具箱] 中,按兩下 MonthCalendar 控制項。

    MonthCalendar 控制項會顯示在設計介面上。

  7. 在 [屬性] 視窗中,為 MonthCalendar 控制項設定下列屬性。

    屬性

    Margin

    0,0,0,0

    ShowToday

    False

  8. 設定 VendorControl 的大小以符合 MonthCalendar 控制項的大小。

  9. 選取 MonthCalendar 控制項。

  10. 在 [屬性] 視窗中,按一下 [事件] 索引標籤,然後按兩下 [DateChanged] 事件。

    VendorControl 檔案隨即在 [程式碼編輯器] 中開啟,而且 [DateChanged] 事件的事件處理常式會加入其中。

  11. 將現有的程式碼更換成下列程式碼。 這個程式碼會定義 Date 屬性和一些邏輯,將 MonthCalendar 控制項的日期範圍屬性、SelectionStartSelectionEnd 限制為和 TodayDate 相同的值。 這個程式碼也會實作使用於 WPF 資料繫結的 INotifyPropertyChanged 介面。

    Imports System
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Drawing
    Imports System.Data
    Imports System.Linq
    Imports System.Text
    Imports System.Windows.Forms
    
    Public Class VendorControl
        Inherits UserControl
        Implements INotifyPropertyChanged
    
        <Browsable(True)> _
        Public Property [Date]() As String
            Get
                Return Me.MonthCalendar1.TodayDate.ToShortDateString()
            End Get
    
            Set(ByVal value As String)
                If value <> Me.MonthCalendar1.TodayDate.ToShortDateString() Then
                    Dim newDate As DateTime = DateTime.Parse(value)
                    Me.SetDate(newDate)
                    Me.NotifyPropertyChanged("Date")
                End If
            End Set
        End Property
    
    
        Private Sub monthCalendar1_DateChanged( _
            ByVal sender As Object, ByVal e As DateRangeEventArgs) _
        Handles MonthCalendar1.DateChanged
            Me.SetDate(e.Start)
            Me.NotifyPropertyChanged("Date")
    
        End Sub
    
    
        Private Sub SetDate(ByVal [date] As DateTime)
            Me.MonthCalendar1.TodayDate = [date]
            Me.MonthCalendar1.SelectionStart = [date]
            Me.MonthCalendar1.SelectionEnd = [date]
    
        End Sub
    
    #Region "INotifyPropertyChanged Implementation"
    
        Public Event PropertyChanged As PropertyChangedEventHandler _
            Implements INotifyPropertyChanged.PropertyChanged
    
        Private Sub NotifyPropertyChanged(ByVal info As String)
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
        End Sub
    
    #End Region
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace VendorControlLibrary
    {
        public partial class VendorControl : UserControl, INotifyPropertyChanged
        {
            public VendorControl()
            {
                InitializeComponent();
            }
    
            [Browsable(true)]
            public string Date
            {
                get
                {
                    return this.monthCalendar1.TodayDate.ToShortDateString();
                }
    
                set
                {
                    if (value != this.monthCalendar1.TodayDate.ToShortDateString())
                    {
                        DateTime newDate = DateTime.Parse(value);
                        this.SetDate(newDate);
                        this.OnPropertyChanged("Date");
                    }
                }
            }
    
            private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
            {
                this.SetDate(e.Start);
                this.OnPropertyChanged("Date");
            }
    
            private void SetDate(DateTime date)
            {
                this.monthCalendar1.TodayDate = date;
                this.monthCalendar1.SelectionStart = date;
                this.monthCalendar1.SelectionEnd = date;
            }
    
            #region INotifyPropertyChanged Implementation
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void OnPropertyChanged(string propertyName)
            {
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
    
            #endregion
        }
    }
    
  12. 選取 [建置] 功能表上的 [建置方案],以建置方案。

將 Windows Form 控制項裝載在 WPF 中

您要使用 WindowsFormsHost 項目,在 WPF 應用程式中裝載 VendorControl。

若要在 WPF 中裝載 Windows Form 控制項

  1. 在 [方案總管] 的 HostingMonthCalendar 專案中,加入 VendorControlLibrary 專案的參考。 如需詳細資訊,請參閱 How to: 新增或移除的參照,藉由新增的 [參考] 對話方塊

  2. 在 WPF Designer中開啟 MainWindow.xaml。

  3. 從 [工具箱],將 WindowsFormsHost 控制項拖曳到設計介面。

    WindowsFormsIntegration.dll 組件的參考會加入 HostingMonthCalendar 專案中。

  4. 在 [XAML] 檢視中,以下列標記取代現有的標記。 這個 XAML 會對應 VendorControlLibrary 命名空間,並將 TextBlock 項目繫結至 VendorControl 上的 Date 屬性。

    <Window x:Class="HostingMonthCalendar.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:v="clr-namespace:VendorControlLibrary;assembly=VendorControlLibrary"
        Title="Window1" Height="300" Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>
    
            <WindowsFormsHost Name="Host" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center">
                <v:VendorControl Date="2/2/03" />
            </WindowsFormsHost>
    
            <TextBlock Grid.Row="1" 
                       Text="{Binding ElementName=Host, Path=Child.Date, Mode=OneWay, UpdateSourceTrigger=PropertyChanged }" 
                       HorizontalAlignment="Stretch" 
                       VerticalAlignment="Center" 
                       TextAlignment="Center" 
                       TextDecorations="None" 
                       FontSize="24" />
        </Grid>
    </Window>
    
  5. 從 [偵錯] 功能表中選取 [開始偵錯]。

  6. 按一下 MonthCalendar 控制項以變更目前的日期。 WPF TextBlock 項目會更新為顯示選取的日期。

後續步驟

  • 如果您的控制項會廣泛使用於 WPF 環境中,就可以從 WindowsFormsHost 衍生出自己的類別,並公開 Date 屬性。 這麼做可讓其他 WPF 控制項直接繫結至 Date 屬性,而不需要使用 Path=Child.Date 語法。

  • 您也可以將 WPF 控制項裝載在 Windows Form 中。 如需詳細資訊,請參閱使用 WPF 控制項

請參閱

工作

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

參考

WindowsFormsHost

ElementHost

其他資源

使用 WPF 設計工具中的控制項

移轉和互通性