Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reference the parent form from the WPF control

Tags:

winforms

wpf

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.

like image 731
user496949 Avatar asked Dec 20 '10 10:12

user496949


3 Answers

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)

like image 152
Thomas Levesque Avatar answered Sep 23 '22 09:09

Thomas Levesque


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.

like image 31
ColinE Avatar answered Sep 24 '22 09:09

ColinE


I suggest you

  • expose an event from WPF child control,
  • register to that event from parent when it is created,
  • raise that event whenever you want data from child control,
  • make parent control return data by setting values in custom 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.

like image 29
decyclone Avatar answered Sep 23 '22 09:09

decyclone