简体   繁体   中英

Add Children to element of type Page created in code behind Windows Phone 8.1

I can create a new element of type Page in code behind, but I want to add children elements of type UIElement as I would to a Grid like: myGrid.Children.Add(myUIElement);
I don't have the Children property and setting the Content property does not work.
How can I achieve this?


This is what I have so far, but does not work:

Page myNewPage = new Page();
Grid myGrid = new Grid();
TextBlock myText = new TextBlock();
myText.Text = "I am a TextBlock!";
myGrid.Children.Add(myText);
myNewPage.Content = myGrid;

Frame.Navigate(myNewPage.GetType());

A Page can host a single UIElement in its Content property. To add several children, you have to do it like you would do it in XAML: add a panel that can contain and layout several children and add your elements to that panel.

In your question you talk about a grid called myGrid . You could add and layout your items in myGrid and then set myGrid as yourPage.Content .

Your code correctly builds the page. The problem with your code is that your Frame is navigating to a new instance of Page that is not the one that you created. Frame creates a new instance of the type that you pass as a parameter.

If you want to create a page fully in code, you can simply create class that extends Page and build the page in its constructor:

public class MyPage : Page
{
    public MyPage()
    {
        this.BuildPage();
    }

    private void BuildPage()
    {
        var panel = new StackPanel();
        panel.Children.Add(new TextBlock { Text = "Hello" });
        panel.Children.Add(new TextBlock { Text = "World" });

        this.Content = panel;
    }
}

That's, after all, what the InitializeComponent method does in pages created in XAML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM