以通用方式从可视化树中删除项目
我想从可视化树中删除 FrameworkElement。由于 FrameworkElement 有一个 Parent 属性,因此通过从那里删除它来解决这个问题是显而易见的:
FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
// This line will, of course not complie:
// childElement.Parent.RemoveFromChildren(childElement);
}
问题是 FrameworkElement 的 Parent 属性是 DependencyObject 的,它没有子项的概念。因此,我能看到的关于这个问题的唯一方法是通过转换 Parent 来查看它是否是 Border、Panel 等(具有子元素概念的元素)并将其从那里删除:
FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
if(childElement.Parent is Panel)
{
(childElement.Parent as Panel).Children.Remove(childElement );
}
if(childElement.Parent is Border)
{
(childElement.Parent as Border).Child = null;
}
}
显然,这不是一个非常灵活的解决方案,也不是通用的根本不。有人可以建议一种更通用的方法来从可视化树中删除元素吗?
I would like to remove a FrameworkElement from the visual tree. Since the FrameworkElement has a Parent property, it would be obvious to solve this problem by removing it from there:
FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
// This line will, of course not complie:
// childElement.Parent.RemoveFromChildren(childElement);
}
The problem is that the Parent property of FrameworkElement is of DependencyObject, which has no notion of children. So the only thing I can see going about this problem is via casting the Parent to see if it's a Border, Panel etc (elements that have notion of children) and remove it from there:
FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
if(childElement.Parent is Panel)
{
(childElement.Parent as Panel).Children.Remove(childElement );
}
if(childElement.Parent is Border)
{
(childElement.Parent as Border).Child = null;
}
}
Obviously this is not a very flexible solution and not generic at all. Can someone suggest a more generic approach on removing an element from the visual tree?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为没有更简单的方法。实际上,不可能有一种简单的通用方法可以做到这一点。
WPF
非常灵活,您可以使用模板创建自定义控件,该模板需要 3 个子控件通过自定义模板显示在 3 个不同的位置。您能做的最好的事情就是考虑所有基本控件并将它们包含在您的
if-else
梯子中。这些是Panel
、Border
、ContentControl
、ItemsControl
等。I don't think there is a simpler way. Actually, there cannot be an easy generic way to do that.
WPF
is very flexible and you can create a custom control with a template that takes 3 children to display in 3 different places with custom templates.What you can do best is take into account all the basic controls and include them in you
if-else
ladder. These arePanel
,Border
,ContentControl
,ItemsControl
, etc.