WPF FrameworkElement Parent and Moving UIElement

I am trying to move a control from one parent to another (if this works, I'm not quite sure). I can hold on to the control 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 click on the last element, an ArgumentException is thrown, which states that "The specified visual is already a child of another Visual or CompositionTarget root." It is strange that the parent returns null. How to find a parent? Will this work?

EDIT: I don't think that actually moving an element is the answer to my problem. I work with the Visual Studio SDK and was able to hold on to the UIElement that makes up the editor area (extends DockPanel ). I tried to move the control from the standard editor to the custom tool window that I am developing.

This proves that this is a hack, and I realized that I need several instances of the same control, so I think a more complex solution (and less hack) is in stock.

+4
source share
1 answer

The Parent property refers to the logical tree, and the docs state that "the parent can be empty when the element was created, but not tied to the logical tree, which ultimately connects to the root element of the page level, or the application object." For example, the root element of a DataTemplate created in a ListBox has a null parent.

Try using VisualTreeHelper.GetParent . The visual tree is a lower-level view of how WPF elements are organized, and gives you access to all the extra β€œbits” that can be added to templates. For example, a call to VisualTreeHelper.GetParent on the root DataTemplate created in the ListBox returns a ContentPresenter .

Please note that just because you can get the parent visual does not necessarily mean that you can delete it. Some elements, such as panels, provide methods for this. But if the item you find is part of, say, CheckBox , I don’t think you can remove it.

If you can provide a little more context for what you are trying to achieve by moving controls around the visual tree, people can offer more specific recommendations or alternative approaches.

+6
source

Source: https://habr.com/ru/post/1306081/


All Articles