【问题标题】:Find an embedded control within WPF Application在 WPF 应用程序中查找嵌入式控件
【发布时间】:2015-01-13 10:52:59
【问题描述】:

我有一个混合了 WPF 和 Windows 窗体的旧应用程序。本质上,通过将 ElementHost 添加到 Windows 窗体,将 WPF 应用程序加载到 Windows 窗体应用程序中。然后,此 WPF 应用程序将 WPF 用户控件加载到它上面。嵌入在此 WPF 用户控件中的是旧版 Windows 控件(自定义浏览器控件),它最终派生自 System.Windows.Forms

有没有办法从代码中动态获取该控件的句柄?我们不知道控件在呈现时的名称。我们所知道的是控件的基本类型,正如我提到的,它源自 System.WIndows.Forms。

到目前为止,我看到的所有示例都讨论了如何动态发现最终成为 DependencyObject 的子对象。我还没有遇到一个示例来解释如何在 WPF 应用程序中以编程方式发现旧式 Windows 窗体控件。

【问题讨论】:

    标签: wpf winforms elementhost


    【解决方案1】:

    为了在 WPF 控件中托管 Winforms 控件,它必须使用WindowsFormsHost。 WindowsFormsHost 派生自 DependencyObject。

    您必须在 WPF 应用程序中找到 WindowsFormsHost 元素,然后才能访问包含 WebBrowser 控件的 Child 属性。

    伪代码:

    var controlYoureLookingFOr = GiveMeAllChildren(WPFApp)
      .OfType<WindowsFormsHost>
      .First();
    
    var browser = (WebBrowser.Or.Something)controlYoureLookingFOr.Child;
    

    【讨论】:

    • @Nikhil:np。如果您也添加“递归”部分作为您自己的答案或我的一部分,那就太好了。
    【解决方案2】:

    在这里完成答案是我添加的递归部分,以确保遍历整个窗口或父控件及其所有后代

       public static IEnumerable<T> FindAllChildrenByType<T>(this System.Windows.Forms.Control control)
        {
            IEnumerable<System.Windows.Forms.Control> controls = control.Controls.Cast<System.Windows.Forms.Control>();
            return controls
                .OfType<T>()
                .Concat<T>(controls.SelectMany<System.Windows.Forms.Control, T>(ctrl => FindAllChildrenByType<T>(ctrl)));
        }
        public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }
    
                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
    

    然后你就可以把它当作

     var windowsFormHost = parentControl.FindVisualChildren<WindowsFormsHost>();
                foreach (var item in windowsFormHost)
                {
                    var htmlcontrols = item.Child.FindAllChildrenByType<{sometypehere}
                    foreach (var control in htmlcontrols)
                    {
                    }
                 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      相关资源
      最近更新 更多