How to reference a parent form from a WPF control

I am using elementhost to host a WPF user control in window form. I want to know how to reference the parent form in a WPF control.

+7
source share
3 answers

Why not create this relationship programmatically? those. when you add your WPF user control to the element node, set the Tag property for the user control to the instance of the element node.

Colin E.

+3
source

Here is a way to do this, from within the WPF UserControl , which 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); } 

(there is an alias for System.Windows.Forms in this Forms code)

+15
source

I suggest you

  • output event from WPF child control ,
  • register this event from the parent when it is created,
  • raise this event whenever you need data from a child control,
  • return the parent data to return by setting values ​​to the custom EventArgs object.

Access to the parent control should be avoided, if only in some special scenarios. Always propagate events to the parent container from children when you want to establish communication with the child in relation to the parent.

+2
source

All Articles