简体   繁体   English

如何将文本块动态添加到页面?

[英]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. 我只是在学习如何制作适用于Windows 10的通用应用程序。大多数教程都向您展示了如何使用XAML以及如何在单击元素时将功能分配给元素,但是我找不到找到新控件的方法。单击按钮时出现。

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. 我想我必须将新的文本框放在某种Grid类的东西中。

Most of the tutorials are really old or mention windows forms and use some sort of this.Controls.Add(newNote); 大多数教程确实很老,或者提到了Windows窗体,并使用了某种形式的this.Controls.Add(newNote); but Visual studio doesn't give me the Controls.Add option. 但是Visual Studio没有给我Controls.Add选项。 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. 我还创建了一个<Grid x:Name="notes"></Grid> ,我以为可以将其用作正在创建的便笺的占位符,但无法通过代码访问Grid元素。

Container Controls like Grid have Children property so you should use Childern like this: 诸如Grid类的容器控件具有Children属性,因此您应该像下面这样使用Childern

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: 在页面上的XAML中,您可以将notes用作标识符,以从后面的页面代码访问此Grid

notes.Children.Add(newNote);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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