【问题标题】:How can I access programmatically created UI Elements in Xamarin.Forms : timepicker如何访问 Xamarin.Forms 中以编程方式创建的 UI 元素:timepicker
【发布时间】:2020-06-11 14:26:46
【问题描述】:

我有一个以编程方式创建 UI 元素的方法。示例:

Label label1 = new Label(); 
label1.Text = "Testlabel";

TimePicker timepicker1 = new TimePicker();
timepicker1.Time = new TimeSpan(07, 00, 00);

之后,我将它们都添加到已经存在的 StackLayout 中。

stacklayout1.Children.Add(label1);
stacklayout1.Children.Add(timepicker1);

我的应用程序的用户可以多次创建它。 现在我的问题是,我怎样才能访问,例如,创建的第二个/更好的所有 TimePickers?

【问题讨论】:

  • stackLayout1.Children[x] 或使用命名引用timepicker1

标签: xaml xamarin xamarin.forms uielement


【解决方案1】:

一些建议:

使用ID:

var id = label1.Id;
var text = (stacklayout1.Children.Where(x => x.Id == id).FirstOrDefault() as myLabel).Text;

使用索引:

Label labelOne = stacklayout1.Children[0] as Label;

使用标签:

为标签创建自定义属性tag:

public class myLabel : Label{ 

    public int tag { get; set; }
}

并通过标签查找标签:

var labels = stacklayout1.Children.Where(x => x is myLabel).ToList();

foreach (myLabel childLabel in labels)
{
  if (childLabel.tag == 0)
  {

  }
}

顺便说一句,如果你在 xaml 中创建标签,你可以使用findbyname:

Label label = stacklayout1.FindByName("labelA") as Label;

【讨论】:

    【解决方案2】:
    var timepickers = stacklayout1.Children.Where(child => child is TimePicker);
    

    将返回添加到您的 StackLayout 的所有时间选择器的 IEnumerable。您还必须将 using System.Linq 添加到页面顶部的 usings 中。

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 2017-06-08
      • 1970-01-01
      相关资源
      最近更新 更多