0

In JavaScript I can loop through a series of elements fairly easily, like so:

var x = 0;
while (document.getElementById("MyElement-" + x)) {
    // Do something    

    x++;
}

What would be the equivalent of doing this in C# with WPF elements?

<Grid x:Name="MyElement_0" />
<Grid x:Name="MyElement_1" />
<Grid x:Name="MyElement_2" />
<!-- Etc... -->

Thanks!

  • 3
    My suggestion is: **you don't**. It seems like it's an X/Y problem here. What are you _actually_ trying to achieve? – dymanoid Nov 09 '18 at 14:44
  • There are some options in this question: https://stackoverflow.com/questions/636383/how-can-i-find-wpf-controls-by-name-or-type but @dymanoid is right, generally you don't need to get an element by name. You either know the name, or you iterate though an Items collection or similar. – Robin Bennett Nov 09 '18 at 14:47
  • So I have a thousand elements inside a grid. Those thousand elements are represented in a listbox. When a user clicks on a listbox item I need to be sure all elements are hidden and then the coresponding element clicked in the listbox is shown. (listbox index goes with the WPF element name) –  Nov 09 '18 at 14:55
  • 1
    Some changes in the mindset: if you do this in CSS, you can set the one selected as visible while others hidden without having to give each of the elements an id, they just need to be classified as “selected” and “unselected” in CSS. Same technique exists in WPF. – kennyzx Nov 09 '18 at 15:00
  • That makes sense. Thanks! –  Nov 09 '18 at 15:31

0 Answers0