xamlxamarinxamarin.formsuielement

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


I got a method which 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?


Solution

  • 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;