Reputation: 3218
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?
UPDATE:
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());
Upvotes: 1
Views: 4144
Reputation: 9303
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.
Upvotes: 2