简体   繁体   English

每次按下按钮时如何添加条目

[英]How to add entries every time a button is pressed

I am making a mobile app using Xamarin Forms and I am writing all of my code including the visual aspects in c# (in the.cs files).我正在使用 Xamarin Forms 制作一个移动应用程序,并且我正在编写我的所有代码,包括 c# 中的视觉方面(在.cs文件中)。 Essentially I need to be able to add a new entry every time a button is pressed and then get the text entered into said entry.本质上,我需要能够在每次按下按钮时添加一个新条目,然后将文本输入到所述条目中。

Right now I can create a new Entry and give it a name that I can use to reference it:现在我可以创建一个新条目并给它一个可以用来引用它的名称:

private Entry entry1;
Layout.Children.Add(entry1 = new Entry
{
//entry code
});

//when some button is pressed
string entry1Text = entry1.Text;

I want to make it so that every time the user presses a button, it creates a new entry, but I also need to be able to get the text from it.我想让它每次用户按下按钮时都会创建一个新条目,但我还需要能够从中获取文本。 How can I make it so that it creates a new entry with a new name like entry2, entry3, etc... without manually writing out like 10 entries and then making them visible?我怎样才能让它创建一个新名称的新条目,如 entry2、entry3 等......而无需手动写出 10 个条目然后使它们可见? I need to do this because I don't know how many entries the user will add (could be more than 10).我需要这样做,因为我不知道用户将添加多少条目(可能超过 10 个)。

int numberOfEntries = 1;
void addEntry_Clicked(object sender, EventArgs e)
{
    string entryNumber = numberOfEntries.ToString();

    //the following 2 lines are what doesn't work with the name of an entry, but is what I want to do
    private Entry entry + entryNumber;
    Layout.Children.Add(entry + entryNumber = new Entry
    {
        //entry code
    });

    numberOfEntries+=1;
}

//some button is pressed
string entryText = (entry + entryNumber).Text;

The problem is I can't add a number to the name of an entry like entry +"2" Is this even possible for me to do?问题是我不能在条目的名称中添加一个数字,比如 entry +"2" 这对我来说是否可行?

you need to keep a separate data structure to track your controls, like this您需要保留一个单独的数据结构来跟踪您的控件,就像这样

Dictionary<string,Entry> entries = new Dictionary<string,Entry>();

private void AddEntry(string name)
{
  var entry = new Entry();
  myLayout.Children.Add(entry);
  entries.Add(name,entry);
}

then you can get their value like this那么你可以像这样得到他们的价值

var text = entries["entryA"].Text; 

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

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