0
votes

I can't figure out how to call several similarly named WPF TextBlocks in a for loop.

In WPF I have several TextBlocks that are each inside of a grid cell:

<TextBlock Name="Banner0" />
<TextBlock Name="Banner1" />
<TextBlock Name="Banner2" />

For example those three are in Grid.Row="0" Grid.Column="0", Grid.Row="0" Grid.Column="1", Grid.Row="0" Grid.Column="2", respectively.

In C# I am able to change the text in the above TextBlocks with the following code:

Banner0.Text = "Sample Text";
Banner1.Text = "Sample Text";
Banner2.Text = "Sample Text";

However what I want to do, but can't figure out how to do is change it this way.

for (int i = 0; i < 3; i++) 
   { 
       Banneri.Text = "Sample Text"; 
   }

I understand why I can't do Banneri, but can't figure out how to achieve that concept within a for loop.

Also the text will not be the same in each TextBlock, but for simplicity I used "Sample Text" in all three, as this is not the area that is causing difficulty.

1
The Text property of the individual TextBlocks should be bound to a property in view model, e.g. in a collection of data item objects. Search the web for MVVM.Clemens
Otherwise, a simple array like var textBlocks = new TextBlock[] { Banner0, Banner1, Banner2 } should also work.Clemens
You could also iterate over all TextBlock children of their parent common parent element: foreach (var textblock in panel.Children.OfType<TextBlock>()) { … }Clemens
Thanks for your suggestions! The MVVM opened a whole rabbit hole, of stuff I was unaware of. Will delve into that more.SeanM
I was trying to do the children method, but think I either don't grasp it enough. Or my WPF is not laid out correct. But the Array does work, and for the time, will be using that. Thanks!SeanM

1 Answers

1
votes

The easiest way to iterate them would probably be to put them in an array.

// put them together
TextBlock[] banners = new [] {Banner0, Banner1, Banner2};

// iterate like this
for(var i = 0; i < banners.Length; i++){
    banners[i].Text = "Sample Text";
}