How do I add UI Children to an empty WPF-Page?

2020-04-20 13:50发布

问题:

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?

回答1:

First of all, the Window.AddChild will throw an exception when you add more than one object to it, because Window is a ContentControl. Page allowes only 1 child .So you set the child using the Page.Content property. So you want to add a container to your Page and then add children to the container.
For example:

Button b = new Button();
b.Content = "Hello";
StackPanel myPanel = new StackPanel();
myPanel.Children.Add(b);
this.Content = myPanel;


回答2:

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 the Page to the Stackpanel.

Here is an lazy example in the constructor of a MainWindow.

public MainWindow()
{
    InitializeComponent();

    StackPanel panel = new StackPanel();
    Button b1 = new Button {Content = "Hello"};
    Button b2 = new Button {Content = "Hi"};

    panel.Children.Add(b1);
    panel.Children.Add(b2);

    Page page = new Page {Content = panel};

    this.Content = page;
}