Move a UserControl from a ContentControl to another one programmatically
Asked Answered
W

2

6

In a WPF app I want to move a UserControl from a ContentControl to another one in code:

 myContentControl2.Content = myUserControl;

in this case I get an error:
Specified element is already the logical child of another element. Disconnect it first.

In a ControlControl class description I can see a RemoveVisualChild method, but when I try to use it in code I get an Unknown method error

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

Where am I wrong?
How to move a UserControl from a ContentControl to another one in code-behind?

Wherry answered 30/1, 2012 at 10:18 Comment(2)
@Maheep: yes, with what i answered.Viviennevivify
@Clemens: Yep. What I have updated is same as your answer. But I tried the solution independently and updated. I am Ok with your answer as accepted one. But happy about I too learned it.Orris
V
2

Set

myContentControl1.Content = null;

to remove myUserControl from myContentControl1 before setting

myContentControl2.Content = myUserControl;

By the way, don't confuse the logical tree with the visual tree. Get more information in Trees in WPF in the MSDN.

Viviennevivify answered 30/1, 2012 at 10:33 Comment(1)
Yes, it works, thank you! And your note about trees is helpful as well, +1Wherry
O
1

In a ControlControl class description I can see a RemoveVisualChild method, but when I try to use it in code I get an Unknown method error

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

Better option is to remove myUserControl from logical tree of myContentControl1 before adding it some other control's logical tree. To achieve this you can set the Content property of myContentControl1 to something else or to null.

Orris answered 30/1, 2012 at 10:30 Comment(1)
Thank you for making it clear about using protected methods, +1Wherry

© 2022 - 2024 — McMap. All rights reserved.