How to count Label controls count in Xamarin?
-
Hi, I want to write a code like this that runs perfectly in WinForms:
int count = 0;
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(Label))
if (((Label)c).BackColor == Color.Red)
count++;
}But in Xamarin, I cannot use Control class. There is no namespace for it. How can I do the same in Xamarin?
-
Hi, I want to write a code like this that runs perfectly in WinForms:
int count = 0;
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(Label))
if (((Label)c).BackColor == Color.Red)
count++;
}But in Xamarin, I cannot use Control class. There is no namespace for it. How can I do the same in Xamarin?
Your WinForms code would be better written as:
int count = 0;
foreach (Label l in this.Controls.OfType<Label>())
{
if (l.BackColor == Color.Red)
{
count++;
}
}Or simply:
int count = this.Controls.OfType<Label>().Count(l => l.BackColor == Color.Red);
Xamarin forms doesn't have a similar concept. You might be able to do something similar by walking the visual tree - eg: the urban canuk, eh: VisualTreeHelper for Xamarin.Forms[^] However, it would almost certainly be better to use MVVM concepts to achieve your goal.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer