获取Window的视觉内容
我目前有这行代码,我想在所有情况下工作:
var visualWindowContent = (UIElement)window.Content;
当 Window.Content 是 UIElement 时,此方法将起作用。但是,当它是一个非可视对象并应用了 DataTemplate 时该怎么办?上面的代码行会抛出错误的强制转换异常。那么在这种情况下如何获取窗口的视觉内容呢?
编辑: 起初我说 VisualTreeHelper.GetChild(window, 0) 返回 null,但实际上它是非 null 的。我的目的是通过将 VisualWindowContent 传递给 AdornerLayer.GetAdornerLayer 来获取根装饰器层。事实证明,当传递窗口的直接视觉子节点时失败(返回 null),因为该节点在视觉树中不够深,即 AdornerDectorator 的后代。
I currently have this line of code which I want to work in all cases:
var visualWindowContent = (UIElement)window.Content;
This approach will work when Window.Content is a UIElement. But what about when it's a non-visual object which then has a DataTemplate applied to it? The above line of code would throw a bad cast exception. So how to get the window's visual content in that case?
EDIT: At first I said that VisualTreeHelper.GetChild(window, 0) returned null, but it was in fact non-null. My purpose here is to get the root adorner layer by passing visualWindowContent to AdornerLayer.GetAdornerLayer. It turns out that was failing (returning null) when passed the window's immediate visual child since that node wasn't deep enough in the visual tree, i.e. a descendant of AdornerDectorator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 @ReedCopsey 链接的页面中的 FindVisualChild 方法,这似乎有效:
Using the FindVisualChild method in the page linked by @ReedCopsey, this appears to work:
如果您想要内容本身,则可以只使用对象:
这在所有情况下都有效,因为内容将是 UIElement 或实际分配的对象。
如果您尝试查找通过数据模板创建的元素,请参阅查找 DataTemplate-在 MSDN 上生成元素以获取选项。这是通过查找
ContentPresenter
并检查它的ContentTemplate
来完成的。If you want the content itself, you can just use the object:
This will work in all cases, as the content will be a UIElement or the object actually assigned.
If you're trying to find the elements created via the data template, see Find DataTemplate-Generated Elements on MSDN for options. This is done via finding the
ContentPresenter
, and inspecting it'sContentTemplate
.