0

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

2 Answers2

0
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.

James Mallon
  • 1,107
  • 9
  • 25
0

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;
nevermore
  • 15,432
  • 1
  • 12
  • 30