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

此生再无相见时 提交于 2019-12-20 05:10:32

问题


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;
}


来源:https://stackoverflow.com/questions/33830751/how-do-i-add-ui-children-to-an-empty-wpf-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!