2

I have a series of controls that can be passed around and on occasion they are added as a child to another control.

In many cases I cannot know for certain if the control is currently the child of another control.

For example :

Label lbl = new Label( );
/*Stuff happens; lbl may be assigned or not; whatever.*/
//If the label has already been assigned as a child to a viewbox
if ( lbl.Parent is Viewbox )
    return lbl.Parent;
else {
    if (lbl.Parent != null )
        //Of course this fails because there is no lbl.Parent.Child property.
        lbl.Parent.Child = null;
    return new Viewbox( ) { Child = lbl, Stretch = Stretch.Uniform };
}

It is entirely possible I am completely misinterpreting the function of the Control.Parent property.

Is it possible to orphan a control from it's parent through the control itself?

Will
  • 3,413
  • 7
  • 50
  • 107
  • 3
    Just a hint: don't do this. WPF is all about XAML, don't create/remove views in code-behind. You'll run into troubles very quickly. – dymanoid Feb 18 '16 at 16:34
  • yeah i know all about that but there are some instances in which I have to work in code behind, like if I'm populating a grid control with a bunch of other controls, each of which has an item from a list as part of their data context since I don't know how to populate a grid with a list of controls like that in XAML alone. – Will Feb 18 '16 at 16:41
  • 1
    Use `DataTemplate` or `DataTemplateSelector`. – dymanoid Feb 18 '16 at 16:43
  • @dymanoid I will look into that. I do hate doing it "wrong" but my limited experience inhibits my ability to do it "right". – Will Feb 18 '16 at 18:36

1 Answers1

3
void RemoveElementFromItsParent(FrameworkElement el)
{
    if (el.Parent == null)
        return;

    var panel = el.Parent as Panel;
    if (panel != null)
    {
        panel.Children.Remove(el);
        return;
    }

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

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

    var contentControl = el.Parent as ContentControl;
    if (contentControl != null)
        contentControl.Content = null;
}

source: https://stackoverflow.com/a/19318405/1271037

dovid
  • 6,354
  • 3
  • 33
  • 73
  • 1
    This is not neat. Why this? `if (panel != null) panel?.Children...` – dymanoid Feb 18 '16 at 16:57
  • It's a bit clunky but I think this should get me on the right path. – Will Feb 18 '16 at 17:55
  • 2
    Google found for me also [this answer](https://stackoverflow.com/a/19318405/1997232), @dovid, please add attribution to author if its the case, otherwise you may be blamed in plagiarism. – Sinatr Nov 15 '18 at 08:26