Move UserControl from ContentControl to another programmatically

In a WPF application, I want to move UserControl from ContentControl to another code:

myContentControl2.Content = myUserControl; 

in this case, I get an error:
The specified element is already a logical child of another element. Disable it first.

In the description of the ControlControl class, I see the RemoveVisualChild method , but when I try to use it in the code, I get an unknown method error

 myContentControl1.RemoveVisualChild(myUserControl);//here I get an "Unknown method" error 

Where am I mistaken?
How to transfer UserControl from ContentControl to another in code?

+6
source share
2 answers

Set

 myContentControl1.Content = null; 

remove myUserControl from myContentControl1 before setting up

 myContentControl2.Content = myUserControl; 

By the way, do not confuse the logical tree with the visual tree. Get more information in Trees in WPF on MSDN.

+2
source

In the description of the ControlControl class, I see the RemoveVisualChild method, but when I try to use it in the code, I get an unknown method error

This is because RemoveVisualChild and RemoveLogicalChild are protected methods that you cannot directly access in your class. If you want to use this method, create a derived class from ContentControl and release these methods using some public method wrapper in this class.

It is best to remove myUserControl from the logical tree myContentControl1 before adding it to another control logical tree. To do this, you can set the Content property to myContentControl1 something else or null .

+1
source

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


All Articles