I am using elementhost to host the WPF user control within a windows form. I want to know how to reference the parent form within WPF control.
Here's a way to do it, from within a WPF UserControl
that has a button in it:
private void button1_Click(object sender, RoutedEventArgs e)
{
var source = (HwndSource)PresentationSource.FromDependencyObject(button1);
var host = (Forms.Integration.ElementHost)Forms.Control.FromChildHandle(source.Handle);
var form = (Forms.Form)host.TopLevelControl;
// Show form title
MessageBox.Show(form.Text);
}
(in this code Forms
is an alias for System.Windows.Forms
)
Why not create this relationship programmatically? i.e. when you add your WPF user control into an element host, set the Tag property of the user control to the element host instance.
Colin E.
I suggest you
WPF child control
, EventArgs
object.Accessing a parent control should be avoided unless in some special scenarios. Always propagate events to parent container from children when want to setup communication from child to parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With