Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF FrameworkElement Parent and Moving a UIElement

I'm trying to move a control from one parent to another (if this will work I'm not quite sure). I can get a hold of the control that I want to move. Here is my code:

public void MoveElement(UIElement uiElement)
{
    var element = ((FrameworkElement)uiElement).Parent;
    //TODO:Remove from parent
    myControl.Children.Add(uiElement);
}

When I hit the last statment an ArgumentException is thrown stating "Specified Visual is already a child of another Visual or the root of a CompositionTarget." The strange thing is that Parent is returning null. How do locate the parent? Will this even work?

EDIT: I don't think actually moving an element is the answer to my problem. I'm working with the Visual Studio SDK and was able to get a hold of the UIElement that makes up the editor pane (extends DockPanel). I was trying to move the control from the standard editor into a custom tool window I'm developing.

This is proving to be a hack and I realized that I need multiple instances of the same control so I think a more complex solution (and less of a hack) is in store.

like image 307
Adam Driscoll Avatar asked Apr 06 '10 04:04

Adam Driscoll


1 Answers

The Parent property refers to the logical tree, and the docs note that "Parent may be null in cases where an element was instantiated, but is not attached to any logical tree that eventually connects to the page level root element, or the application object." For example, the root element of a DataTemplate instantiated in a ListBox has a null Parent.

Try using VisualTreeHelper.GetParent instead. The visual tree is the lower-level representation of how WPF elements are organised, and gives you access to all the extra "bits" that things like templating throw in there. For example, calling VisualTreeHelper.GetParent on the root element of a DataTemplate instantiated in a ListBox returns a ContentPresenter.

Note that just because you can get hold of the parent visual does not necessarily mean you'll be able to remove it. Some elements, such as Panels, provide methods for this. But if the element you locate is part of, say, a CheckBox, I don't think you'll be able to remove it.

If you can provide a bit more context for what you're trying to achieve by moving controls around the visual tree, people may be able to offer more specific advice or alternative approaches.

like image 90
itowlson Avatar answered Oct 31 '22 06:10

itowlson