Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.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_Silverlight_Visual Tree - Fatal编程技术网

Wpf 以常规方式从可视树中删除项目

Wpf 以常规方式从可视树中删除项目,wpf,silverlight,visual-tree,Wpf,Silverlight,Visual Tree,我想从可视化树中删除FrameworkElement。由于FrameworkElement具有父属性,因此很明显可以通过将其从父属性中删除来解决此问题: FrameworkElement childElement; if(childElement != null && childElement.Parent != null) // In the visual tree { // This line will, of course not complie: // chi

我想从可视化树中删除FrameworkElement。由于FrameworkElement具有父属性,因此很明显可以通过将其从父属性中删除来解决此问题:

FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
   // This line will, of course not complie:
   // childElement.Parent.RemoveFromChildren(childElement);
}
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;
   }
}
问题是FrameworkElement的父属性是DependencyObject,它没有子级的概念。因此,我能看到的唯一一件关于这个问题的事情是通过铸造父元素来查看它是否是边框、面板等(具有子元素概念的元素),并从中移除它:

FrameworkElement childElement;
if(childElement != null && childElement.Parent != null) // In the visual tree
{
   // This line will, of course not complie:
   // childElement.Parent.RemoveFromChildren(childElement);
}
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;
   }
}

显然,这不是一个非常灵活的解决方案,也不是通用的。有人能推荐一种更通用的方法从可视化树中删除元素吗?

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


您能做的最好的事情是考虑所有基本控件,并将它们包含在您的
if-else
ladder中。它们是
面板
边框
内容控制
项目控制
,等等。

遗憾的是,对于带有子项的项目,没有通用接口。谢谢你的列表,我还没有想到ContentControl或ItemsControl。。。现在这就行了@Gergely:我在MSDN上看到一篇关于WPF中内容模型的文章。我想这可能对你有用。