captain
captain

Reputation: 1827

How do I add a textblock dynamically to a page?

I'm just learning how to make universal apps for windows 10. Most of the tutorials show you how to work with XAML and how to assign functions to elements when you click on them but I couldn't find a way to make a new control appear when I click a button.

I'm making a note taking application. I've designed most of the stuff that I need. Now I want whenever I click a button to create a new textblock where the user can write their note.

    //Create a new note when clicking the add button
    private void newNoteBtn_Click(object sender, RoutedEventArgs e)
    {

        TextBox newNote = new TextBox();
        newNote.Text = "Enter your text";
    }

This is the code that runs when the button is clicked. When I run the application nothing happens. I think I have to put the new textbox in some kind of Grid or something.

Most of the tutorials are really old or mention windows forms and use some sort of this.Controls.Add(newNote); but Visual studio doesn't give me the Controls.Add option. I've also created a <Grid x:Name="notes"></Grid> which I thought I could use as a placeholder for the notes that are being created but I can't access the Grid element through the code.

Upvotes: 1

Views: 2029

Answers (2)

andreask
andreask

Reputation: 4298

When defining

<Grid x:Name="notes"></Grid>

in XAML on the page, you be able to use notes as the identifier to access this Grid from the page's code behind:

notes.Children.Add(newNote);

Upvotes: 2

Salah Akbari
Salah Akbari

Reputation: 39956

Container Controls like Grid have Children property so you should use Childern like this:

TextBox newNote = new TextBox();
newNote.Text = "Enter your text";
notes.Childern.Add(newNote);

Upvotes: 3

Related Questions