I'm having a MainWindow which is a NavigationWindow. Inside this MainWindow I want to switch in several Pages. One of the Pages has to be dynamically generated by Code, not by XAML. When I had a normal window before, I could add UI components like this:
Button b = new Button();
b.Content = "Hello";
this.AddChild(b);
Or if I added (for example) a StackPanel with this method first, I could add Children to this StackPanel with:
myPanel.Children.Add(b);
However, the Page Class doesn't have a Children Attribute or a AddChild Method. The only method I found so far is:
AddVisualChild(b);
The page shows but I don't see any components which I added with this method. So how do I add Children to a WPF-Page correctly?
I'm not really sure if this works for you but you could try to set the content of a page to a user control. E.g. use a
StackPanel
and add all the children to it. After that you set the content of thePage
to theStackpanel
.Here is an lazy example in the constructor of a MainWindow.
First of all, the
Window.AddChild
will throw an exception when you add more than one object to it, becauseWindow
is aContentControl
.Page
allowes only 1 child .So you set the child using thePage.Content
property. So you want to add a container to yourPage
and then add children to the container.For example: