Поделиться через


Пошаговое руководство. Сопоставление свойств с помощью элемента управления ElementHost

В этом пошаговом руководстве показано, как использовать свойство PropertyMap для сопоставления свойств Windows Forms с соответствующими свойствами в размещенном элементе WPF.

Задачи, показанные в этом пошаговом руководстве, включают:

  • Создание проекта.

  • Определение нового сопоставления свойств.

  • Удаление сопоставления свойств по умолчанию.

  • Расширение сопоставления свойств по умолчанию.

По завершении вы сможете сопоставить свойства Windows Forms с соответствующими свойствами WPF в размещенном элементе.

Необходимые условия

Для выполнения этого пошагового руководства вам потребуется следующее:

  • Visual Studio 2017

Создание проекта

Создание проекта

  1. Создайте проект приложения Windows Forms с именем .

  2. В Solution Explorerдобавьте ссылки на следующие сборки WPF.

    • PresentationCore

    • PresentationFramework

    • WindowsBase

    • WindowsFormsIntegration

  3. Скопируйте следующий код в начало файла кода Form1.

    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Forms.Integration;
    
    Imports System.Windows
    Imports System.Windows.Media
    Imports System.Windows.Media.Imaging
    Imports System.Windows.Forms.Integration
    
  4. Откройте Form1 в конструкторе Windows Forms. Дважды щелкните форму, чтобы добавить обработчик событий для события Load.

  5. Вернитесь в конструктор Windows Forms и добавьте обработчик событий для события Resize формы. Дополнительные сведения см. в разделе Практическое руководство. Создание обработчиков событий с помощью конструктора.

  6. Объявите поле ElementHost в классе Form1.

    ElementHost elemHost = null;
    
    Private elemHost As ElementHost = Nothing
    

Определение новых сопоставлений свойств

Элемент управления ElementHost предоставляет несколько сопоставлений свойств по умолчанию. Добавление нового сопоставления свойства осуществляется путем вызова метода Add для PropertyMapэлемента управления ElementHost.

Определение новых сопоставлений свойств

  1. Скопируйте следующий код в определение для класса Form1.

    // The AddMarginMapping method adds a new property mapping
    // for the Margin property.
    private void AddMarginMapping()
    {
        elemHost.PropertyMap.Add(
            "Margin",
            new PropertyTranslator(OnMarginChange));
    }
    
    // The OnMarginChange method implements the mapping
    // from the Windows Forms Margin property to the
    // Windows Presentation Foundation Margin property.
    //
    // The provided Padding value is used to construct
    // a Thickness value for the hosted element's Margin
    // property.
    private void OnMarginChange(object h, String propertyName, object value)
    {
        ElementHost host = h as ElementHost;
        Padding p = (Padding)value;
        System.Windows.Controls.Button wpfButton =
            host.Child as System.Windows.Controls.Button;
    
        Thickness t = new Thickness(p.Left, p.Top, p.Right, p.Bottom );
    
        wpfButton.Margin = t;
    }
    
    ' The AddMarginMapping method adds a new property mapping
    ' for the Margin property.
    Private Sub AddMarginMapping()
    
        elemHost.PropertyMap.Add( _
            "Margin", _
            New PropertyTranslator(AddressOf OnMarginChange))
    
    End Sub
    
    
    ' The OnMarginChange method implements the mapping 
    ' from the Windows Forms Margin property to the
    ' Windows Presentation Foundation Margin property.
    '
    ' The provided Padding value is used to construct 
    ' a Thickness value for the hosted element's Margin
    ' property.
    Private Sub OnMarginChange( _
    ByVal h As Object, _
    ByVal propertyName As String, _
    ByVal value As Object)
    
        Dim host As ElementHost = h
        Dim p As Padding = CType(value, Padding)
        Dim wpfButton As System.Windows.Controls.Button = host.Child
    
    
        Dim t As New Thickness(p.Left, p.Top, p.Right, p.Bottom)
    
        wpfButton.Margin = t
    
    End Sub
    

    Метод AddMarginMapping добавляет новое сопоставление для свойства Margin.

    Метод OnMarginChange преобразует свойство Margin в свойство Margin WPF.

  2. Скопируйте следующий код в определение для класса Form1.

    // The AddRegionMapping method assigns a custom
    // mapping for the Region property.
    private void AddRegionMapping()
    {
        elemHost.PropertyMap.Add(
            "Region",
            new PropertyTranslator(OnRegionChange));
    }
    
    // The OnRegionChange method assigns an EllipseGeometry to
    // the hosted element's Clip property.
    private void OnRegionChange(
        object h,
        String propertyName,
        object value)
    {
        ElementHost host = h as ElementHost;
        System.Windows.Controls.Button wpfButton =
            host.Child as System.Windows.Controls.Button;
    
        wpfButton.Clip = new EllipseGeometry(new Rect(
            0,
            0,
            wpfButton.ActualWidth,
            wpfButton.ActualHeight));
    }
    
    // The Form1_Resize method handles the form's Resize event.
    // It calls the OnRegionChange method explicitly to
    // assign a new clipping geometry to the hosted element.
    private void Form1_Resize(object sender, EventArgs e)
    {
        this.OnRegionChange(elemHost, "Region", null);
    }
    
    ' The AddRegionMapping method assigns a custom 
    ' mapping for the Region property.
    Private Sub AddRegionMapping()
    
        elemHost.PropertyMap.Add( _
            "Region", _
            New PropertyTranslator(AddressOf OnRegionChange))
    
    End Sub
    
    
    ' The OnRegionChange method assigns an EllipseGeometry to
    ' the hosted element's Clip property.
    Private Sub OnRegionChange( _
    ByVal h As Object, _
    ByVal propertyName As String, _
    ByVal value As Object)
    
        Dim host As ElementHost = h
    
        Dim wpfButton As System.Windows.Controls.Button = host.Child
    
        wpfButton.Clip = New EllipseGeometry(New Rect( _
            0, _
            0, _
            wpfButton.ActualWidth, _
            wpfButton.ActualHeight))
    
    End Sub
    
    
    ' The Form1_Resize method handles the form's Resize event.
    ' It calls the OnRegionChange method explicitly to 
    ' assign a new clipping geometry to the hosted element.
    Private Sub Form1_Resize( _
    ByVal sender As Object, _
    ByVal e As EventArgs) Handles MyBase.Resize
    
        If elemHost IsNot Nothing Then
            Me.OnRegionChange(elemHost, "Region", Nothing)
        End If
    
    End Sub
    

    Метод AddRegionMapping добавляет новое сопоставление для свойства Region.

    Метод OnRegionChange преобразует свойство Region в свойство Clip WPF.

    Метод Form1_Resize обрабатывает событие Resize формы и изменяет размер области вырезки, чтобы соответствовать размещенному элементу.

Удаление сопоставления свойств по умолчанию

Удалите сопоставление свойств по умолчанию, вызвав метод Remove в PropertyMapэлемента управления ElementHost.

Удаление сопоставления свойств по умолчанию

  • Скопируйте следующий код в определение для класса Form1.

    // The RemoveCursorMapping method deletes the default
    // mapping for the Cursor property.
    private void RemoveCursorMapping()
    {
        elemHost.PropertyMap.Remove("Cursor");
    }
    
    ' The RemoveCursorMapping method deletes the default
    ' mapping for the Cursor property.
    Private Sub RemoveCursorMapping()
        elemHost.PropertyMap.Remove("Cursor")
    End Sub
    

    Метод RemoveCursorMapping удаляет сопоставление по умолчанию для свойства Cursor.

Расширение сопоставления свойств по умолчанию

Вы можете использовать сопоставление свойств по умолчанию, а также расширить его с помощью собственного сопоставления.

Для расширения сопоставления свойств по умолчанию

  • Скопируйте следующий код в определение для класса Form1.

    // The ExtendBackColorMapping method adds a property
    // translator if a mapping already exists.
    private void ExtendBackColorMapping()
    {
        if (elemHost.PropertyMap["BackColor"] != null)
        {
            elemHost.PropertyMap["BackColor"] +=
                new PropertyTranslator(OnBackColorChange);
        }
    }
    
    // The OnBackColorChange method assigns a specific image
    // to the hosted element's Background property.
    private void OnBackColorChange(object h, String propertyName, object value)
    {
        ElementHost host = h as ElementHost;
        System.Windows.Controls.Button wpfButton =
            host.Child as System.Windows.Controls.Button;
    
        ImageBrush b = new ImageBrush(new BitmapImage(
            new Uri(@"file:///C:\WINDOWS\Santa Fe Stucco.bmp")));
        wpfButton.Background = b;
    }
    
    ' The ExtendBackColorMapping method adds a property
    ' translator if a mapping already exists.
    Private Sub ExtendBackColorMapping()
    
        If elemHost.PropertyMap("BackColor") IsNot Nothing Then
    
            elemHost.PropertyMap("BackColor") = PropertyTranslator.Combine( _
                elemHost.PropertyMap("BackColor"), _
                PropertyTranslator.CreateDelegate( _
                GetType(PropertyTranslator), _
                Me, _
                "OnBackColorChange"))
        End If
    
    End Sub
    
    
    ' The OnBackColorChange method assigns a specific image 
    ' to the hosted element's Background property.
    Private Sub OnBackColorChange( _
    ByVal h As Object, _
    ByVal propertyName As String, _
    ByVal value As Object)
    
        Dim host As ElementHost = h
        Dim wpfButton As System.Windows.Controls.Button = host.Child
        Dim b As New ImageBrush(New BitmapImage( _
            New Uri("file:///C:\WINDOWS\Santa Fe Stucco.bmp")))
        wpfButton.Background = b
    
    End Sub
    

    Метод ExtendBackColorMapping добавляет переводчик настраиваемых свойств в существующее сопоставление свойств BackColor.

    Метод OnBackColorChange назначает определенное изображение свойству Background размещенного элемента управления. Метод OnBackColorChange вызывается после применения сопоставления свойств по умолчанию.

Инициализация сопоставлений свойств

  1. Скопируйте следующий код в определение для класса Form1.

    private void Form1_Load(object sender, EventArgs e)
    {
        // Create the ElementHost control.
        elemHost = new ElementHost();
        elemHost.Dock = DockStyle.Fill;
        this.Controls.Add(elemHost);
    
        // Create a Windows Presentation Foundation Button element
        // and assign it as the ElementHost control's child.
        System.Windows.Controls.Button wpfButton = new System.Windows.Controls.Button();
        wpfButton.Content = "Windows Presentation Foundation Button";
        elemHost.Child = wpfButton;
    
        // Map the Margin property.
        this.AddMarginMapping();
    
        // Remove the mapping for the Cursor property.
        this.RemoveCursorMapping();
    
        // Add a mapping for the Region property.
        this.AddRegionMapping();
    
        // Add another mapping for the BackColor property.
        this.ExtendBackColorMapping();
    
        // Cause the OnMarginChange delegate to be called.
        elemHost.Margin = new Padding(23, 23, 23, 23);
    
        // Cause the OnRegionChange delegate to be called.
        elemHost.Region = new Region();
    
        // Cause the OnBackColorChange delegate to be called.
        elemHost.BackColor = System.Drawing.Color.AliceBlue;
    }
    
    Private Sub Form1_Load( _
    ByVal sender As Object, _
    ByVal e As EventArgs) Handles MyBase.Load
    
        ' Create the ElementHost control.
        elemHost = New ElementHost()
        elemHost.Dock = DockStyle.Fill
        Me.Controls.Add(elemHost)
    
        ' Create a Windows Presentation Foundation Button element 
        ' and assign it as the ElementHost control's child. 
        Dim wpfButton As New System.Windows.Controls.Button()
        wpfButton.Content = "Windows Presentation Foundation Button"
        elemHost.Child = wpfButton
    
        ' Map the Margin property.
        Me.AddMarginMapping()
    
        ' Remove the mapping for the Cursor property.
        Me.RemoveCursorMapping()
    
        ' Add a mapping for the Region property.
        Me.AddRegionMapping()
    
        ' Add another mapping for the BackColor property.
        Me.ExtendBackColorMapping()
    
        ' Cause the OnMarginChange delegate to be called.
        elemHost.Margin = New Padding(23, 23, 23, 23)
    
        ' Cause the OnRegionChange delegate to be called.
        elemHost.Region = New [Region]()
    
        ' Cause the OnBackColorChange delegate to be called.
        elemHost.BackColor = System.Drawing.Color.AliceBlue
    
    End Sub
    

    Метод Form1_Load обрабатывает событие Load и выполняет следующую инициализацию.

    • Создает элемент Button WPF.

    • Вызывает методы, определенные ранее в пошаговом руководстве, чтобы настроить сопоставления свойств.

    • Назначает начальные значения сопоставленным свойствам.

  2. Нажмите клавишу F5, чтобы создать и запустить приложение.

См. также