I have a WPF application with many labels.
<Label x:Name="label1" />
<Label x:Name="label2" />
<Label x:Name="label3" />
....
I dont want give every label a value one by one like:
label1.content= 1;
label2.content= 20;
label3.content= 30;
....
I want do it more like this:
for(int i = 1; i<40 ;i++)
{
label"i".content = i*10;
}
Is there any way to do that?
If your labels are all named consistently, you can do it like this:
var numberOfLabels = 40;
for(int i = 1; i <= numberOfLabels; i++)
{
var labelName = string.Format("label{0}", i);
var label = (Label) this.FindName(labelName);
label.Content = i * 10;
}
If you work with binding it is easy. You just have to keep your label content in an ObservableCollection<string>
on your ViewModel. And then, you can do whatever you want with them, in your case iteration.
Edit 1:
Also your xaml should be something like:
<ItemsControl ItemsSource="{Binding MyLabelValues}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<sdk:Label Content="{Binding Mode=TwoWay}"></sdk:Label>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Using this code
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
You can enumerate all controls by type.
foreach (Label lbl in FindVisualChildren<Label>(window))
{
// do something with lbl here
}
You could add all those Label
to a List<Label>
within the form's constructor.
It is a tedious work, but you'll only have to do it once.
List<Label> labels = new List<Label>();
labels.Add(label1);
// etc.
// loop
for (int i = 0; i < labels.Count; i++)
labels[i].Text = i.ToString();
// alternative loop
foreach (Label label in labels)
label.Text = "test";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With