【问题标题】:Xamarin Forms - retrieve value of dynamically added entry control value on button clickXamarin Forms - 在按钮单击时检索动态添加的条目控件值的值
【发布时间】:2017-03-20 06:41:03
【问题描述】:

我想在点击button 时获取所有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++)
            {
                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
        }

【问题讨论】:

  • 您应该使用MVVM 和数据绑定来获取值,这是错误的方式。您应该使用 ListView 而不是其中包含多个条目的 StackLayout,您应该使用 Entry 创建 ItemTemplate 并将 Text 属性绑定到某个模型。
  • @AkashKava 感谢您的回复,能否提供一些示例或示例数据?
  • 对不起@AkashKava,但示例代码链接不起作用

标签: xamarin xamarin.forms


【解决方案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
           }


 }

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多