Home > OS >  How to access methods and properties of WPF control from WinForms?
How to access methods and properties of WPF control from WinForms?

Time:09-27

There is a control created in the library of custom controls that contains ONLY RichTextBox (System.Windows.Controls.RichTextBox). It is added to a WinForms form.

The problem is to access its methods and properties.

When using var rich = elementHost1.Child as System.Windows.Controls.RichTextBox, the rich variable contains null.

CodePudding user response:

WpfControlLibrary1.UserControl1

If I understood your explanation correctly, then try this:

    WpfControlLibrary1.UserControl1 control = 
        (WpfControlLibrary1.UserControl1) elementHost1.Child;
    System.Windows.Controls.RichTextBox rich = 
        (System.Windows.Controls.RichTextBox) control.Content;

System.InvalidCastException: "Unable to cast object of type "System.Windows.Controls.Grid" to type "System.Windows.Controls.RichTextBox"."

Then you did not correctly explain "that contains ONLY RichTextBox".

Need to change the code to take into account the Grid:

    WpfControlLibrary1.UserControl1 control = 
        (WpfControlLibrary1.UserControl1) elementHost1.Child;
    System.Windows.Controls.Grid grid = 
        (System.Windows.Controls.Grid) control.Content;
    System.Windows.Controls.RichTextBox rich = 
        (System.Windows.Controls.RichTextBox) grid.Children[0];
  • Related