0

I am trying to show a group variables that contains a string from the code behind (C#) to Textblock in XAML using the code below:

 Textblock1.Text = String1Class;
 Textblock2.Text = String2Class;
 Textblock3.Text = String3Class;
 Textblock4.Text = String4Class;
 Textblock5.Text = String5Class;
 Textblock6.Text = String6Class;

The code works but its a pain writing the same thing over and over again. I want to ask if there is a better way. I know it has to do with arrays and loops, but I am not very familiar with C# and WPF.

3 Answers 3

1

Given the fact that you have separate variables for each of the StringXClass values you need to do this if you want to keep the variables the same:

var tbs = new [] { Textblock1, Textblock2, Textblock3, Textblock4, Textblock5, Textblock6, };
var scs = new [] { String1Class, String2Class, String3Class, String4Class, String5Class, String6Class, };

for (var i = 0; i < tbs.Length; i++)
{
    tbs.Text = scs;
}

The alternative is to set up an array in the first place.

var StringClass = new string[6];

Then replace String1Class with StringClass[0], String2Class with StringClass[1], etc, in your code.

Then write this:

var tbs = new [] { Textblock1, Textblock2, Textblock3, Textblock4, Textblock5, Textblock6, };
for (var i = 0; i < tbs.Length; i++)
{
    tbs.Text = StringClass[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

This did it! Thanks!
0

You can loop through the TextBlocks if they are in the same parent:

string controlName = "TextBlock";
int startIndex = 1;
int endIndex = 100;

List<string>  stringList = new List<string>();
for(int i = 0; i < 100 ; i++)
    stringList.Add("string"+(i+1).ToString());

for(int i = startIndex; i<=endIndex; i++)
{
    foreach(control c in TextBlock1.Parent.Controls)//Or if you know the actual parent to which all the textBoxes belong
    {
        if(c.Name == (controlName+i))
        {               
            (c as TextBlock).Text = stringsList[i-1]; //since our start index starts with 1. 
            break;                   
        }
    }
}

Comments

0

XAML:

<StackPanel>
    <TextBlock Name="TextBlock1"></TextBlock>
    <TextBlock Name="TextBlock2"></TextBlock>
    <TextBlock Name="TextBlock3"></TextBlock>
    <TextBlock Name="TextBlock4"></TextBlock>
</StackPanel>

Code:

TextBlock[] textboxes = { TextBlock1, TextBlock2, TextBlock3, TextBlock4 };
string[] list = { "TextBlock 1", "TextBlock 2", "TextBlock 3", "TextBlock 4" };

for (int i = 0; i < textboxes.Length; i++)
{
    textboxes[i].Text = list[i];
}

Output:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.