Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 获取窗口的可视内容_Wpf_Window_Contentcontrol_Visual Tree - Fatal编程技术网

Wpf 获取窗口的可视内容

Wpf 获取窗口的可视内容,wpf,window,contentcontrol,visual-tree,Wpf,Window,Contentcontrol,Visual Tree,我目前有一行代码,我希望在所有情况下都能使用: 当Window.Content是一个UIElement时,这种方法将起作用。但是,如果它是一个非可视对象,并且应用了一个数据模板,该怎么办呢?上述代码行将引发错误的强制转换异常。那么,在这种情况下,如何获取窗口的视觉内容呢 编辑:起初我说VisualTreeHelper.GetChildwindow 0返回null,但实际上它不是null。我在这里的目的是通过将visualWindowContent传递给AdornerLayer.GetAdorne

我目前有一行代码,我希望在所有情况下都能使用:

当Window.Content是一个UIElement时,这种方法将起作用。但是,如果它是一个非可视对象,并且应用了一个数据模板,该怎么办呢?上述代码行将引发错误的强制转换异常。那么,在这种情况下,如何获取窗口的视觉内容呢


编辑:起初我说VisualTreeHelper.GetChildwindow 0返回null,但实际上它不是null。我在这里的目的是通过将visualWindowContent传递给AdornerLayer.GetAdornerLayer来获取根adorner层。当传递窗口的直接视觉子节点时,返回null失败,因为该节点在视觉树中的深度不够,即AdornerDectorator的后代。

如果您想要内容本身,可以使用对象:

object visualWindowContent = window.Content;
这在所有情况下都有效,因为内容将是UIElement或实际指定的对象


如果要查找通过数据模板创建的元素,请参阅MSDN上的选项。这是通过查找ContentPresenter并检查其ContentTemplate来完成的。

在@ReedCopsey链接的页面中使用FindVisualChild方法,这似乎是可行的:

var contentPresenter = FindVisualChild<ContentPresenter>( window );
var visualWindowContent = (UIElement)VisualTreeHelper.GetChild( contentPresenter, 0 );

我想要所有情况下的视觉效果请填写问号:var cp=FindVisualChild窗口;var visualWindowContent=UIElementcp.ContentTemplate.FindName???,cp;
var contentPresenter = FindVisualChild<ContentPresenter>( window );
var visualWindowContent = (UIElement)VisualTreeHelper.GetChild( contentPresenter, 0 );