简体   繁体   中英

How can I access programmatically created UI Elements in Xamarin.Forms : timepicker

I got a method wich is creating UI Element programmatically. Example:

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

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

After that I add both of them in an already existing StackLayout.

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

A user of my app can create this multiple times. Now my question is, how can I access, for example, the second/ better all of TimePickers which were created?

Thank you in advance!

var timepickers = stacklayout1.Children.Where(child => child is TimePicker);

Will return an IEnumerable of all of the timepickers added to your StackLayout. You will have to also add using System.Linq to your usings at the top of the page.

Some suggestions:

Use ID :

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

Use index :

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

Use tag :

Create a custom property tag to the label:

public class myLabel : Label{ 

    public int tag { get; set; }
}

And find label by the tag:

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

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

  }
}

BTW, if you create the label in xaml , you can use findbyname :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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