Looping over XAML defined labels

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
}

Tags:

C#

.Net

Loops

Wpf