Loading content from a WPF page into ContentControl

I am looking for a way to swap the contents of part of my application to predefined pages. I got to ContentControl , but I cannot copy content from my pages. The code I used was

 ContentControl1.Content = new PageName().Content 

which gave me an exception stating that the Specified element is already the logical child of another element. Disconnect it first. Specified element is already the logical child of another element. Disconnect it first.

Can I load a page in ContentControl ?

Alternatively, is it possible to use the Visual Studio constructor in some way to create pages and store them in a way that is easier to load into ContentControl ?

And finally, it will make my day, but is there a way that I can contain content inside the ContentControl call methods declared in Window that contain it?

+6
wpf
source share
2 answers

Edit2: To load a page, you need to remove the content control and use Frame or the navigation window .

Edit:. I read the question again and realized that you are using the page, the solution below works only for user controls. You will still receive an error message if you try to create a page object.

To load a user control in a content control, you can try something like:

 ContentControl1.Content = new UserControl(); 

I don’t think that calling methods from the main window inside the control would be a good idea, but if you want to do this, you can pass an instance of the window to the page constructor and use it to call methods from the main window.

+3
source share

In order for a window to be able to handle "events" of user control / content, you must understand that there are less ore than windows, you need to know in advance which events can be raised. When switching a large number of pages, this can lead to a huge load of handlers in the window that can be called.

The best option would be to store the data (model) in the window and the design / code logic in user controls that manipulate the data. You can easily get the data by assigning it to the DataContext property of the window. Then the DataContext of the loaded UserControl will return the data.

This setting will improve the service code.

+2
source share

All Articles