Xaml 如何访问Xamarin中以编程方式创建的UI元素
我得到了一个方法,它以编程方式创建UI元素。例如:Xaml 如何访问Xamarin中以编程方式创建的UI元素,xaml,xamarin,xamarin.forms,uielement,Xaml,Xamarin,Xamarin.forms,Uielement,我得到了一个方法,它以编程方式创建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.Ch
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);
我的应用程序的用户可以多次创建此项。
现在我的问题是,我如何访问,例如,创建的第二个/更好的时间选择器
提前谢谢你
var timepickers = stacklayout1.Children.Where(child => child is TimePicker);
将返回添加到StackLayout的所有时间选择器的IEnumerable。您还必须将using System.Linq添加到页面顶部的using中。一些建议:
使用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;
使用索引:
var id = label1.Id;
var text = (stacklayout1.Children.Where(x => x.Id == id).FirstOrDefault() as myLabel).Text;
Label labelOne = stacklayout1.Children[0] as Label;
使用标记:
var id = label1.Id;
var text = (stacklayout1.Children.Where(x => x.Id == id).FirstOrDefault() as myLabel).Text;
Label labelOne = stacklayout1.Children[0] as Label;
为标签创建自定义属性标记
:
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;
stackLayout1.Children[x]
或使用命名引用timepicker1