Procédure pas à pas : mappage de propriétés à l'aide de l'élément WindowsFormsHost

Cette procédure pas à pas vous montre comment utiliser la PropertyMap propriété pour mapper les propriétés WPF aux propriétés correspondantes sur un contrôle Windows Forms hébergé.

Cette procédure pas à pas décrit notamment les tâches suivantes :

  • Création du projet.

  • Définition de la disposition de l’application.

  • Définition d’un nouveau mappage de propriété.

  • Suppression d’un mappage de propriété par défaut.

  • Remplacement d’un mappage de propriété par défaut.

  • Extension d’un mappage de propriété par défaut.

Lorsque vous avez terminé, vous pourrez mapper les propriétés WPF aux propriétés correspondantes sur un contrôle Windows Forms hébergé.

Prérequis

Vous devez disposer des éléments suivants pour exécuter cette procédure pas à pas :

  • Visual Studio 2017

Créer et configurer le projet

  1. Créez un projet d’application WPF nommé PropertyMappingWithWfhSample.

  2. Dans Explorateur de solutions, ajoutez une référence à l’assembly WindowsFormsIntegration, nommé WindowsFormsIntegration.dll.

  3. Dans Explorateur de solutions, ajoutez des références aux assemblys System.Drawing et System.Windows.Forms.

Définition de la disposition de l’application

L’application WPF utilise l’élément WindowsFormsHost pour héberger un contrôle Windows Forms.

Pour définir la disposition de l’application

  1. Ouvrez Window1.xaml dans le Concepteur WPF.

  2. Remplacez le code existant par le code ci-dessous.

    <Window x:Class="PropertyMappingWithWfh.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PropertyMappingWithWfh" Height="300" Width="300"
        Loaded="WindowLoaded">
      <DockPanel Name="panel1" LastChildFill="True">
        <WindowsFormsHost Name="wfHost" DockPanel.Dock="Left" SizeChanged="Window1_SizeChanged" FontSize="20" />
      </DockPanel>
    </Window>
    
  3. Ouvrez Window1.xaml.cs dans l’éditeur de code.

  4. En haut du fichier, importez les espaces de noms suivants.

    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Windows.Forms;
    using System.Windows.Forms.Integration;
    
    Imports System.Drawing
    Imports System.Drawing.Drawing2D
    Imports System.Windows.Forms
    Imports System.Windows.Forms.Integration
    

Définition d’un nouveau mappage de propriété

L’élément WindowsFormsHost fournit plusieurs mappages de propriétés par défaut. Vous ajoutez un nouveau mappage de propriétés en appelant la Add méthode sur l’élémentPropertyMapWindowsFormsHost.

Pour définir un nouveau mappage de propriété

  • Copiez le code suivant dans la définition de la Window1 classe.

    // The AddClipMapping method adds a custom
    // mapping for the Clip property.
    private void AddClipMapping()
    {
        wfHost.PropertyMap.Add(
            "Clip",
            new PropertyTranslator(OnClipChange));
    }
    
    // The OnClipChange method assigns an elliptical clipping
    // region to the hosted control's Region property.
    private void OnClipChange(object h, String propertyName, object value)
    {
        WindowsFormsHost host = h as WindowsFormsHost;
        System.Windows.Forms.CheckBox cb = host.Child as System.Windows.Forms.CheckBox;
    
        if (cb != null)
        {
            cb.Region = this.CreateClipRegion();
        }
    }
    
    // The Window1_SizeChanged method handles the window's
    // SizeChanged event. It calls the OnClipChange method explicitly
    // to assign a new clipping region to the hosted control.
    private void Window1_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        this.OnClipChange(wfHost, "Clip", null);
    }
    
    // The CreateClipRegion method creates a Region from an
    // elliptical GraphicsPath.
    private Region CreateClipRegion()
    {
        GraphicsPath path = new GraphicsPath();
    
        path.StartFigure();
    
        path.AddEllipse(new System.Drawing.Rectangle(
            0,
            0,
            (int)wfHost.ActualWidth,
            (int)wfHost.ActualHeight ) );
    
        path.CloseFigure();
    
        return( new Region(path) );
    }
    
    ' The AddClipMapping method adds a custom mapping 
    ' for the Clip property.
    Private Sub AddClipMapping()
    
        wfHost.PropertyMap.Add( _
            "Clip", _
            New PropertyTranslator(AddressOf OnClipChange))
    
    End Sub
    
    ' The OnClipChange method assigns an elliptical clipping 
    ' region to the hosted control's Region property.
    Private Sub OnClipChange( _
    ByVal h As Object, _
    ByVal propertyName As String, _
    ByVal value As Object)
    
        Dim host As WindowsFormsHost = h
    
        Dim cb As System.Windows.Forms.CheckBox = host.Child
    
        If cb IsNot Nothing Then
            cb.Region = Me.CreateClipRegion()
        End If
    
    End Sub
    
    ' The Window1_SizeChanged method handles the window's 
    ' SizeChanged event. It calls the OnClipChange method explicitly 
    ' to assign a new clipping region to the hosted control.
    Private Sub Window1_SizeChanged( _
    ByVal sender As Object, _
    ByVal e As SizeChangedEventArgs)
    
        Me.OnClipChange(wfHost, "Clip", Nothing)
    
    End Sub
    
    ' The CreateClipRegion method creates a Region from an
    ' elliptical GraphicsPath.
    Private Function CreateClipRegion() As [Region] 
        Dim path As New GraphicsPath()
        
        path.StartFigure()
        
        path.AddEllipse(New System.Drawing.Rectangle( _
            0, _
            0, _
            wfHost.ActualWidth, _
            wfHost.ActualHeight))
        
        path.CloseFigure()
        
        Return New [Region](path)
    
    End Function
    

    La AddClipMapping méthode ajoute un nouveau mappage pour la Clip propriété.

    La OnClipChange méthode traduit la Clip propriété en propriété Windows FormsRegion .

    La Window1_SizeChanged méthode gère l’événement de la fenêtre et dimensionne la région de SizeChanged découpage pour qu’elle corresponde à la fenêtre d’application.

Suppression d’un mappage de propriété par défaut

Supprimez un mappage de propriétés par défaut en appelant la Remove méthode sur l’élément WindowsFormsHostPropertyMap.

Pour supprimer un mappage de propriété par défaut

  • Copiez le code suivant dans la définition de la Window1 classe.

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

    La RemoveCursorMapping méthode supprime le mappage par défaut de la Cursor propriété.

Remplacement d’un mappage de propriété par défaut

Remplacez un mappage de propriété par défaut en supprimant le mappage par défaut et en appelant la Add méthode sur l’élément WindowsFormsHostPropertyMap.

Pour remplacer un mappage de propriété par défaut

  • Copiez le code suivant dans la définition de la Window1 classe.

    // The ReplaceFlowDirectionMapping method replaces the
    // default mapping for the FlowDirection property.
    private void ReplaceFlowDirectionMapping()
    {
        wfHost.PropertyMap.Remove("FlowDirection");
    
        wfHost.PropertyMap.Add(
            "FlowDirection",
            new PropertyTranslator(OnFlowDirectionChange));
    }
    
    // The OnFlowDirectionChange method translates a
    // Windows Presentation Foundation FlowDirection value
    // to a Windows Forms RightToLeft value and assigns
    // the result to the hosted control's RightToLeft property.
    private void OnFlowDirectionChange(object h, String propertyName, object value)
    {
        WindowsFormsHost host = h as WindowsFormsHost;
        System.Windows.FlowDirection fd = (System.Windows.FlowDirection)value;
        System.Windows.Forms.CheckBox cb = host.Child as System.Windows.Forms.CheckBox;
    
        cb.RightToLeft = (fd == System.Windows.FlowDirection.RightToLeft ) ?
            RightToLeft.Yes : RightToLeft.No;
    }
    
    // The cb_CheckedChanged method handles the hosted control's
    // CheckedChanged event. If the Checked property is true,
    // the flow direction is set to RightToLeft, otherwise it is
    // set to LeftToRight.
    private void cb_CheckedChanged(object sender, EventArgs e)
    {
        System.Windows.Forms.CheckBox cb = sender as System.Windows.Forms.CheckBox;
    
        wfHost.FlowDirection = ( cb.CheckState == CheckState.Checked ) ?
                System.Windows.FlowDirection.RightToLeft :
                System.Windows.FlowDirection.LeftToRight;
    }
    
    ' The ReplaceFlowDirectionMapping method replaces the
    ' default mapping for the FlowDirection property.
    Private Sub ReplaceFlowDirectionMapping()
    
        wfHost.PropertyMap.Remove("FlowDirection")
    
        wfHost.PropertyMap.Add( _
            "FlowDirection", _
            New PropertyTranslator(AddressOf OnFlowDirectionChange))
    End Sub
    
    
    ' The OnFlowDirectionChange method translates a 
    ' Windows Presentation Foundation FlowDirection value 
    ' to a Windows Forms RightToLeft value and assigns
    ' the result to the hosted control's RightToLeft property.
    Private Sub OnFlowDirectionChange( _
    ByVal h As Object, _
    ByVal propertyName As String, _
    ByVal value As Object)
    
        Dim host As WindowsFormsHost = h
    
        Dim fd As System.Windows.FlowDirection = _
            CType(value, System.Windows.FlowDirection)
    
        Dim cb As System.Windows.Forms.CheckBox = host.Child
    
        cb.RightToLeft = IIf(fd = System.Windows.FlowDirection.RightToLeft, _
            RightToLeft.Yes, _
            RightToLeft.No)
    
    End Sub
    
    
    ' The cb_CheckedChanged method handles the hosted control's
    ' CheckedChanged event. If the Checked property is true,
    ' the flow direction is set to RightToLeft, otherwise it is
    ' set to LeftToRight.
    Private Sub cb_CheckedChanged( _
    ByVal sender As Object, _
    ByVal e As EventArgs)
    
        Dim cb As System.Windows.Forms.CheckBox = sender
    
        wfHost.FlowDirection = IIf(cb.CheckState = CheckState.Checked, _
        System.Windows.FlowDirection.RightToLeft, _
        System.Windows.FlowDirection.LeftToRight)
    
    End Sub
    

    La ReplaceFlowDirectionMapping méthode remplace le mappage par défaut pour la FlowDirection propriété.

    La OnFlowDirectionChange méthode traduit la FlowDirection propriété en propriété Windows FormsRightToLeft .

    La cb_CheckedChanged méthode gère l’événement CheckedChanged sur le CheckBox contrôle. Elle affecte la FlowDirection propriété en fonction de la valeur de la CheckState propriété

Extension d’un mappage de propriété par défaut

Vous pouvez utiliser un mappage de propriété par défaut et l’étendre avec votre propre mappage.

Pour étendre un mappage de propriété par défaut

  • Copiez le code suivant dans la définition de la Window1 classe.

    // The ExtendBackgroundMapping method adds a property
    // translator if a mapping already exists.
    private void ExtendBackgroundMapping()
    {
        if (wfHost.PropertyMap["Background"] != null)
        {
            wfHost.PropertyMap["Background"] += new PropertyTranslator(OnBackgroundChange);
        }
    }
    
    // The OnBackgroundChange method assigns a specific image
    // to the hosted control's BackgroundImage property.
    private void OnBackgroundChange(object h, String propertyName, object value)
    {
        WindowsFormsHost host = h as WindowsFormsHost;
        System.Windows.Forms.CheckBox cb = host.Child as System.Windows.Forms.CheckBox;
        ImageBrush b = value as ImageBrush;
    
        if (b != null)
        {
            cb.BackgroundImage = new System.Drawing.Bitmap(@"C:\WINDOWS\Santa Fe Stucco.bmp");
        }
    }
    
    ' The ExtendBackgroundMapping method adds a property
    ' translator if a mapping already exists.
    Private Sub ExtendBackgroundMapping() 
        If wfHost.PropertyMap("Background") IsNot Nothing Then
    
            wfHost.PropertyMap("Background") = PropertyTranslator.Combine( _
            wfHost.PropertyMap("Background"), _
            PropertyTranslator.CreateDelegate( _
                GetType(PropertyTranslator), _
                Me, _
                "OnBackgroundChange"))
        End If
    
    End Sub
    
    
    ' The OnBackgroundChange method assigns a specific image 
    ' to the hosted control's BackgroundImage property.
    Private Sub OnBackgroundChange(ByVal h As Object, ByVal propertyName As String, ByVal value As Object) 
        Dim host As WindowsFormsHost = h 
        Dim cb As System.Windows.Forms.CheckBox = host.Child 
        Dim b As ImageBrush = value 
        
        If Not (b Is Nothing) Then
            cb.BackgroundImage = New System.Drawing.Bitmap("C:\WINDOWS\Santa Fe Stucco.bmp")
        End If
    
    End Sub
    

    La ExtendBackgroundMapping méthode ajoute un traducteur de propriétés personnalisé au mappage de propriétés existant Background .

    La OnBackgroundChange méthode affecte une image spécifique à la propriété du BackgroundImage contrôle hébergé. La OnBackgroundChange méthode est appelée après l’application du mappage de propriétés par défaut.

Initialisation de vos mappages de propriétés

Configurez vos mappages de propriétés en appelant les méthodes décrites précédemment dans le gestionnaire d’événements Loaded .

Pour initialiser vos mappages de propriétés

  1. Copiez le code suivant dans la définition de la Window1 classe.

    // The WindowLoaded method handles the Loaded event.
    // It enables Windows Forms visual styles, creates
    // a Windows Forms checkbox control, and assigns the
    // control as the child of the WindowsFormsHost element.
    // This method also modifies property mappings on the
    // WindowsFormsHost element.
    private void WindowLoaded(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.Application.EnableVisualStyles();
    
        // Create a Windows Forms checkbox control and assign
        // it as the WindowsFormsHost element's child.
        System.Windows.Forms.CheckBox cb = new System.Windows.Forms.CheckBox();
        cb.Text = "Windows Forms checkbox";
        cb.Dock = DockStyle.Fill;
        cb.TextAlign = ContentAlignment.MiddleCenter;
        cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
        wfHost.Child = cb;
    
        // Replace the default mapping for the FlowDirection property.
        this.ReplaceFlowDirectionMapping();
    
        // Remove the mapping for the Cursor property.
        this.RemoveCursorMapping();
    
        // Add the mapping for the Clip property.
        this.AddClipMapping();
    
        // Add another mapping for the Background property.
        this.ExtendBackgroundMapping();
    
        // Cause the OnFlowDirectionChange delegate to be called.
        wfHost.FlowDirection = System.Windows.FlowDirection.LeftToRight;
    
        // Cause the OnClipChange delegate to be called.
        wfHost.Clip = new RectangleGeometry();
    
        // Cause the OnBackgroundChange delegate to be called.
        wfHost.Background = new ImageBrush();
    }
    
    ' The WindowLoaded method handles the Loaded event.
    ' It enables Windows Forms visual styles, creates 
    ' a Windows Forms checkbox control, and assigns the
    ' control as the child of the WindowsFormsHost element. 
    ' This method also modifies property mappings on the 
    ' WindowsFormsHost element.
    Private Sub WindowLoaded( _
    ByVal sender As Object, _
    ByVal e As RoutedEventArgs)
    
        System.Windows.Forms.Application.EnableVisualStyles()
    
        ' Create a Windows Forms checkbox control and assign 
        ' it as the WindowsFormsHost element's child.
        Dim cb As New System.Windows.Forms.CheckBox()
        cb.Text = "Windows Forms checkbox"
        cb.Dock = DockStyle.Fill
        cb.TextAlign = ContentAlignment.MiddleCenter
        AddHandler cb.CheckedChanged, AddressOf cb_CheckedChanged
        wfHost.Child = cb
    
        ' Replace the default mapping for the FlowDirection property.
        Me.ReplaceFlowDirectionMapping()
    
        ' Remove the mapping for the Cursor property.
        Me.RemoveCursorMapping()
    
        ' Add the mapping for the Clip property.
        Me.AddClipMapping()
    
        ' Add another mapping for the Background property.
        Me.ExtendBackgroundMapping()
    
        ' Cause the OnFlowDirectionChange delegate to be called.
        wfHost.FlowDirection = System.Windows.FlowDirection.LeftToRight
    
        ' Cause the OnClipChange delegate to be called.
        wfHost.Clip = New RectangleGeometry()
    
        ' Cause the OnBackgroundChange delegate to be called.
        wfHost.Background = New ImageBrush()
    
    End Sub
    

    La WindowLoaded méthode gère l’événement Loaded et effectue l’initialisation suivante.

    • Crée un contrôle Windows FormsCheckBox .

    • Appelle les méthodes que vous avez définies précédemment dans la procédure pas à pas pour configurer les mappages de propriétés.

    • Assigne les valeurs initiales aux propriétés mappées.

  2. Appuyez sur F5 pour générer et exécuter l’application. Cliquez sur la zone case activée pour afficher l’effet du FlowDirection mappage. Quand vous cliquez sur la case à cocher, la disposition inverse son orientation de gauche à droite.

Voir aussi