以通用方式从可视化树中删除项目

发布于 2024-10-07 09:58:29 字数 914 浏览 8 评论 0原文

我想从可视化树中删除 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等风来 2024-10-14 09:58:29

我认为没有更简单的方法。实际上,不可能有一种简单的通用方法可以做到这一点。 WPF 非常灵活,您可以使用模板创建自定义控件,该模板需要 3 个子控件通过自定义模板显示在 3 个不同的位置。

您能做的最好的事情就是考虑所有基本控件并将它们包含在您的 if-else 梯子中。这些是 PanelBorderContentControlItemsControl 等。

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 are Panel, Border, ContentControl, ItemsControl, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文