Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load content from a WPF page in ContentControl

Tags:

.net

wpf

I am looking for a way to swap out the content of a portion of my application with predefined pages. I got as far as the ContentControl, but I can't copy the contents from my pages. The code I used was

ContentControl1.Content = new PageName().Content

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

Is there any way I can load the page in the ContentControl?

Alternatively, is there any way I can use the Visual Studio designer to design pages and store them in a manner that is easier to load in a ContentControl?

And lastly, this would make my day, but is there any way I can have the content inside the ContentControl call methods declared in the Window containing it?

like image 456
Soumya Avatar asked Mar 25 '11 05:03

Soumya


2 Answers

Edit2: In order to be able to load a page you need to remove the content control and use a Frame or a navigation window.

Edit: I've read again the question and realized that your using a Page, the below solution works only for user controls. You'll still get an error if you try it with a Page object.

In order to load a user control in the 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 it you can pass an instance of the Window to the page constructor and use that to call methods from the main window.

like image 129
Adrian Fâciu Avatar answered Oct 02 '22 00:10

Adrian Fâciu


For the window to be able to handle 'events' of the usercontrol/content you have to realize that the windows more ore less needs to know upfront what events could be raised. When switching lots of pages this might lead to a huge load of handlers on the window that might get called.

A better design would be to store the data(model) in the window and design/code logic in the usercontrols that manipulate the data. You can easily get the data by assigning it to the DataContext property of the Window. The DataContext of the loaded UserControl will then return the data.

This setup will lead to you to better maintainable code.

like image 38
Emond Avatar answered Oct 01 '22 22:10

Emond