WPF FrameworkElement Parent and Moving a UIElement
Asked Answered
L

1

6

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.

La answered 6/4, 2010 at 4:16 Comment(0)
N
7

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.

Nonpayment answered 6/4, 2010 at 4:41 Comment(1)
Notice my edits for updated info. I did not know that the VisualTreeHelper existed. That should help me to identify the parent. I'm not quite sure that moving the control is actually what I need to achieve.La

© 2022 - 2024 — McMap. All rights reserved.