Leggere in inglese

Condividi tramite


Procedura dettagliata: Mappatura delle proprietà tramite il controllo ElementHost

Questa procedura dettagliata illustra come utilizzare la proprietà PropertyMap per eseguire il mapping delle proprietà di Windows Form alle proprietà corrispondenti in un elemento WPF ospitato.

Le attività illustrate in questa procedura dettagliata includono:

  • Creazione del progetto.

  • Definizione di una nuova mappatura di proprietà.

  • Rimozione di un mapping di proprietà predefinito.

  • Estensione di una mappatura di proprietà predefinita.

Al termine, sarà possibile eseguire il mapping delle proprietà di Windows Form alle proprietà WPF corrispondenti in un elemento ospitato.

Prerequisiti

Per completare questa procedura dettagliata sono necessari i componenti seguenti:

  • Visual Studio 2017

Creazione del progetto

Per creare il progetto

  1. Creare un progetto di app Windows Forms denominato PropertyMappingWithElementHost.

  2. In Esplora soluzioni, aggiungere i riferimenti agli assembly WPF seguenti.

    • PresentationCore

    • PresentationFramework

    • WindowsBase

    • WindowsFormsIntegration

  3. Copiare il codice seguente nella parte superiore del file di codice Form1.

    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Forms.Integration;
    
  4. Aprire Form1 nel Designer di Windows Form. Fare doppio clic sul modulo per aggiungere un gestore eventi per l'evento Load.

  5. Ritornare alla progettazione di Windows Forms e aggiungere un gestore eventi per l'evento Resize del form. Per ulteriori informazioni, vedere Come: Creare gestori di eventi utilizzando il Designer.

  6. Dichiarare un campo ElementHost nella classe Form1.

    ElementHost elemHost = null;
    

Definizione di nuove mappature di proprietà

Il controllo ElementHost fornisce diverse mappature delle proprietà predefinite. Per aggiungere un nuovo mapping di proprietà, chiamare il metodo Add nel PropertyMapdel controllo ElementHost .

Per definire nuove mappature di proprietà

  1. Copiare il codice seguente nella definizione per la classe 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;
    }
    

    Il metodo AddMarginMapping aggiunge un nuovo mapping per la proprietà Margin.

    Il metodo OnMarginChange converte la proprietà Margin nella proprietà Margin WPF.

  2. Copiare il codice seguente nella definizione per la classe 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);
    }
    

    Il metodo AddRegionMapping aggiunge un nuovo mapping per la proprietà Region.

    Il metodo OnRegionChange converte la proprietà Region nella proprietà Clip WPF.

    Il metodo Form1_Resize gestisce l'evento Resize del modulo e ridimensiona l'area di ritaglio in base all'elemento ospitato.

Rimozione di un mapping di proprietà predefinito

Rimuovere un mapping di proprietà predefinito chiamando il metodo Remove nel PropertyMapdel controllo ElementHost .

Per rimuovere un mapping di proprietà predefinito

  • Copiare il codice seguente nella definizione per la classe Form1.

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

    Il metodo RemoveCursorMapping elimina il mapping predefinito per la proprietà Cursor.

Estensione di un mapping di proprietà predefinito

È possibile usare un mapping delle proprietà predefinito ed estenderlo con il proprio mapping.

Per estendere una mappatura di proprietà predefinita

  • Copiare il codice seguente nella definizione per la classe 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;
    }
    

    Il metodo ExtendBackColorMapping aggiunge un traduttore di proprietà personalizzato alla mappa delle proprietà esistente di BackColor.

    Il metodo OnBackColorChange assegna un'immagine specifica alla proprietà Background del controllo ospitato. Il metodo OnBackColorChange viene chiamato dopo l'applicazione del mapping delle proprietà predefinito.

Inizializza le mappature delle proprietà

  1. Copiare il codice seguente nella definizione per la classe 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;
    }
    

    Il metodo Form1_Load gestisce l'evento Load ed esegue l'inizializzazione seguente.

    • Crea un elemento Button WPF.

    • Chiama i metodi definiti in precedenza nella procedura dettagliata per configurare i mapping delle proprietà.

    • Assegna i valori iniziali alle proprietà mappate.

  2. Premere F5 per compilare ed eseguire l'applicazione.

Vedere anche


Risorse aggiuntive

Documentazione