Disconnecting an element from any/unspecified parent container in WPF
NEW:
I propose to use base classes instead of all other listed. Try this code, this 3 classes are the most use cases for your needs. As I understand, it's almost the same as previos ^)
var parent = VisualTreeHelper.GetParent(child);
var parentAsPanel = parent as Panel;
if (parentAsPanel != null)
{
parentAsPanel.Children.Remove(child);
}
var parentAsContentControl = parent as ContentControl;
if (parentAsContentControl != null)
{
parentAsContentControl.Content = null;
}
var parentAsDecorator = parent as Decorator;
if (parentAsDecorator != null)
{
parentAsDecorator.Child = null;
}
OLD: As far as I remember, you can use Visual type as parent type and try to call RemoveVisualChild method.
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
}
}