在任何WPF /未指定父容器断开一个元素 [英] Disconnecting an element from any/unspecified parent container in WPF

查看:1043
本文介绍了在任何WPF /未指定父容器断开一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控件是另一个控件的子(就像所有的非根控制/ elemts在WPF)。
如果我想移动控制到另一个容器我必须首先将其从当前容器断开连接(否则将抛出一个异常)。

I have a control that is a child of another control (as all non-root controls/elemts are in WPF). If I want to move the control to another container I have to disconnect it from its current container first (otherwise an exception is thrown).

如果我知道父母是那么我只能从它的Children集合,内容或任何其删除什么。 ?但是,如果我不知道是什么父容器的类型是什么 - 如何删除子控件然后

If I know what the parent is then I can just remove it from its Children collection, or Content or whatever. But what if I don't know what the parent container's type is - how do I remove the child control then?

在下面的代码示例:我怎么能到SP1移动到另一个容器不知道父母的类型(面板,分组框中...)?

In the code sample below: How would I be able to move "sp1" to another container without knowing the type of the parent (Panel, GroupBox...)?

// Add the child object "sp1" to a container (of any type).
StackPanel sp1 = new StackPanel();
SomeParentControl.Children.Add(sp1);

// Somewhere else in the code. I still have a reference to "sp1" but now I don't know what container it is in. I just want to move the "sp1" object to another parent container.
AnotherParentControl.Content = sp1; // Generates exception: "Must disconnect specified child from current parent Visual before attaching to new parent Visual."



理想我只想写类似:

Ideally I would just like to write something like:

sp1.Parent.RemoveChild(sp1);



不过,我还没有发现这样的事情。

But I haven't found anything like that.

推荐答案

您可以写信与扩展方法一个辅助类:

You may write a helper class with an extension method:

public static class RemoveChildHelper
{
    public static void RemoveChild(this DependencyObject parent, UIElement child)
    {
        var panel = parent as Panel;
        if (panel != null)
        {
            panel.Children.Remove(child);
            return;
        }

        var decorator = parent as Decorator;
        if (decorator != null)
        {
            if (decorator.Child == child)
            {
                decorator.Child = null;
            }
            return;
        }

        var contentPresenter = parent as ContentPresenter;
        if (contentPresenter != null)
        {
            if (contentPresenter.Content == child)
            {
                contentPresenter.Content = null;
            }
            return;
        }

        var contentControl = parent as ContentControl;
        if (contentControl != null)
        {
            if (contentControl.Content == child)
            {
                contentControl.Content = null;
            }
            return;
        }

        // maybe more
    }
}

这篇关于在任何WPF /未指定父容器断开一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆