Search code examples
c#wpfwinformsdelegateselementhost

How to use a delegate between a Winforms Form and a WPF Usercontrol hosted by an elementhost in the Winforms form?


I have a Winforms app (class named Form_WinForms for the example) and I want to add an elementhost control to it in order to host a WPF Usercontrol (named Form_WPF).

But I don't know how to handle the delegates between them: I want to exchange with the Form_WPF controls from the Form_WinForms and vice versa. How could I do ? Thanks

In the example, I just want to modify the text of the control textbox (WPF technologie) by clicking inside a Winforms button.

In Winforms class:

// In Form_WinForms (my main form)

private void btn_Debug_Click(object sender, EventArgs e)
{
    // Form_WPF.GetInstance().Invoke(new ChangeTextBox_WPF(Form_WPF._ChangeTextBox_WPF), Form_WPF.GetInstance().TextBoxDebug, "test"); // what I would have done if Form_WPF was a WinForms form 
    Form_WPF.GetInstance().Dispatcher.Invoke(new ChangeTextBox_WPF(Form_WPF._ChangeTextBox_WPF), Form_WPF.GetInstance().TextBoxDebug, "test");
}

In WPF class:

// In the Usercontrol Form_WPF (which is hosted by an elementhost in Winforms)

private delegate void ChangeTextBox_WPF(System.Windows.Controls.TextBox TextBox, String texte);
public static void _ChangeTextBox_WPF(System.Windows.Controls.TextBox TextBox, String texte) { TextBox.Text = texte; TextBox.Tag = texte; }

private static Form_WPF _Form_WPF;

public static Form_WPF GetInstance()
{
    if (_Form_WPF == null)
    {
        _Form_WPF = new Form_WPF();
    }
    return _Form_WPF;
}

Solution

  • Cast the Child property of the ElementHost to your WPF control type, e.g.:

    Form_WPF wpfControl = elementHost.Host as Form_WPF;
    

    Then you can access any members of the hosted instance as usual.