The labels are on the form and I would like to index them somehow in order to work with them by means of their indices. For this, I decided to create an array of labels, but I do not know how to do it correctly.

  • to address on an index with the purpose only to change contents? - Gardes
  • yes, for example, label [1] .Content = "text"; - Draktharon
  • mvvm using? - Gardes
  • don't use ... - Draktharon
  • 3
    Then use. In this case, such desires will not occur at all. - VladD

3 answers 3

Well, as an option to shove them in the ListBox and contact via Items

 List<Label> labels = new List<Label>() { new Label {Content = "one" }, new Label {Content = "two" } }; lstBox.ItemsSource = labels; ((Label)lstBox.Items[1]).Content = "one"; 

UDP : add existing

 List<Label> labels = new List<Label>() { lb1, lb2, lb3 }; labels[2].Content = "bla-bla"; 
  • and where in this code I add already existing labels to the sheet, for example with the names lbl1, lbl2, lbl3? - Draktharon
  • @RustemValeev, eh, do you get them out of order? that is, they are not in the same list on the form? - Gardes
  • no, no orderliness - Draktharon
  • @RustemValeev, then why turn to the index? So easy to get confused. As an option, I will update the answer how to add existing ones - Gardes
  • @RustemValeev, updated - Gardes

You can collect elements that lie on the form. For example, we write a method that searches for elements on a form and returns us a list of these objects, as follows:

 public static List<T> FindChilds<T>(DependencyObject parent) where T : DependencyObject { if (parent == null) return null; List<T> foundChilds = new List<T>(); int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int index = 0; index < childrenCount; index++) { var child = VisualTreeHelper.GetChild(parent, index); T childType = child as T; if (childType == null) { var result = FindChilds<T>(child); if (result.Any()) { foundChilds.AddRange(result); break; } } else { foundChilds.Add((T)child); } } return foundChilds; } 

And in the right place, we call our method and get a list of objects by type, like this:

 var labels = FindChilds<Label>(Application.Current.MainWindow); 

The VisualTreeHelper class provides helper methods for performing typical tasks related to nodes in a visual tree.


I checked on the buttons ( Button ), threw two buttons on the form ( Import Images and Button ) and called the method, here's the result:

enter image description here

    It is also possible to arrange a foreach for all controls on the form, then check each control by type and, if the type is suitable, add to the array.