简体   繁体   English

如何从 WinForms 访问 WPF 控件的方法和属性?

[英]How to access methods and properties of WPF control from WinForms?

There is a control created in the library of custom controls that contains ONLY RichTextBox (System.Windows.Controls.RichTextBox).在自定义控件库中创建了一个控件,其中仅包含 RichTextBox (System.Windows.Controls.RichTextBox)。 It is added to a WinForms form.它被添加到 WinForms 表单中。

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 .当使用var rich = elementHost1.Child as System.Windows.Controls.RichTextBox时, rich变量包含null

WpfControlLibrary1.UserControl1 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"." System.InvalidCastException:“无法将类型为“System.Windows.Controls.Grid”的 object 转换为类型“System.Windows.Controls.RichTextBox”。

Then you did not correctly explain "that contains ONLY RichTextBox".然后您没有正确解释“仅包含 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM