Xamarin Forms - 在按钮单击时检索动态添加的条目控制值的值

时间:2017-03-20 06:41:03

标签: xamarin xamarin.forms

我想在entry点击上获得所有button个控制值。

我的代码如下 - 这是我在页面上添加动态控件的方式:

        public BookSeat()
        {
            ScrollView scroll = new ScrollView();
            StackLayout stack = new StackLayout();

            int count = Convert.ToInt32(Application.Current.Properties["NoPersonEntry"]);

            for (int i = 0; i < count; i++)
            {
                stack.Children.Add(
                    new StackLayout()
                    {
                        Children = {
                            new Label (){TextColor = Color.Blue, Text = "First Name: ", WidthRequest = 100,StyleId="FnameLabel"+i },
                            new Entry() {StyleId="FnameEntry"+i }
                        }
                    }
                );
            }

            Button button = new Button
            {
                Text = "Save"
            };

            button.Clicked += OnButtonClicked;
            stack.Children.Add(button);

            scroll.Content = stack;
            this.Content = scroll;
        }

以下代码适用于我希望button点击

的价值
        public void OnButtonClicked(object sender, EventArgs e)
        {
           // Here I want to get value
        }

1 个答案:

答案 0 :(得分:1)

您可以做的是将您的条目存储在列表中,以便以后可以访问它们。

例如:

private List<Entry> _myentries = new List<Entry>();

public BookSeat()
        {
            ScrollView scroll = new ScrollView();
            StackLayout stack = new StackLayout();

            int count = Convert.ToInt32(Application.Current.Properties["NoPersonEntry"]);

            for (int i = 0; i < count; i++)
            {
var entry = new Entry() {StyleId="FnameEntry"+i };
_myentries.Add(entry);
                stack.Children.Add(
                    new StackLayout()
                    {
                        Children = {
                            new Label (){TextColor = Color.Blue, Text = "First Name: ", WidthRequest = 100,StyleId="FnameLabel"+i },
                            entry 
                        }
                    }
                );
            }
[...]
        }

现在你可以这样做:

public void OnButtonClicked(object sender, EventArgs e)
        {
           foreach(var entry in _myentries)
           {
              var text = entry.Text;//here we go
           }


 }