Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over XAML defined labels

Tags:

c#

.net

loops

wpf

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?

like image 458
user2261524 Avatar asked Jun 04 '13 14:06

user2261524


4 Answers

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;
}
like image 75
Klaus Byskov Pedersen Avatar answered Sep 18 '22 09:09

Klaus Byskov Pedersen


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>
like image 41
Xelom Avatar answered Sep 21 '22 09:09

Xelom


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
}
like image 26
Cybermaxs Avatar answered Sep 22 '22 09:09

Cybermaxs


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";
like image 20
Nolonar Avatar answered Sep 22 '22 09:09

Nolonar