Japs Asuncion
Japs Asuncion

Reputation: 3

Child(wpf usercontrol) calling a function from Parent(winForm)

I have Form1 (parent) and it has an elementHost (WPF usercontrol). Now, I want that WPF usercontrol to call a function from its parent or pass value/data. Simple as that.

This is the code I'm using but the program is always crashing..

Form1:

public void samp()
{
 MessageBox.Show("Sample");
}

WPF userControl:

Form1 frm1 = new Form1();

public void test()
{
 frm1.samp();
}

Is it possible for the child to access it's parent directly?

Upvotes: 0

Views: 1896

Answers (2)

Fischermaen
Fischermaen

Reputation: 12468

This program can't work! You create a new Form1 in your Wpf usercontrol. Form1 contains this usercontrol... So this is an endless loop!

You have to cast the Parent property of the elementhost hosting your WPF usercontrol to Form1, then you can call your function, like this:

HwndSource wpfHandle = PresentationSource.FromVisual(this) as HwndSource;
if (wpfHandle != null)
{
    ElementHost host = System.Windows.Forms.Control.FromChildHandle(wpfHandle.Handle) as ElementHost;
    if (host != null)
    {
        Form1 form1 = host.Parent as Form1;
        if (form1 != null)
        {
            form1.samp();
        }
    }
}

Upvotes: 4

user572559
user572559

Reputation:

You will have to enject a parental instance into your WPF control. Then having that reference you can manipulate with it.

Upvotes: 0

Related Questions