简体   繁体   中英

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.

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

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

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