Search code examples
c#wpflistrandomtextblock

Edit the content of a text block in a list C# (WPF Application)


So I have five text blocks I've added to a list, and each one is supposed to get its own random number between one and 6.

I know I can just do a new int for each text block (int randomNumberOne, randomNumberTwo, etc) but I'm trying to see if I can figure out how to make a list and a for each loop to work.

Is there some way to edit the content of a TextBox in a list as it goes through? If there is, I haven't found any way to do so.

Here's my code so far.

List<TextBlock> randomBoxList = new List<TextBlock>();

        public MainWindow()
        {
            InitializeComponent();
            randomBoxList.Add(randomBoxOne);
            randomBoxList.Add(randomBoxTwo);
            randomBoxList.Add(randomBoxThree);
            randomBoxList.Add(randomBoxFour);
            randomBoxList.Add(randomBoxFive);
        }

    Random randomGenerator = new Random();
    int randomNumber;

    private void randomButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (TextBlock textBlock in randomBoxList)
        {
            randomNumber = randomGenerator.Next(1, 7);
            //Code to change randomBox content goes here. 
        }
    }

Solution

  • If this is WPF, you should just be able to use textBlock.Text property like so:

     public partial class MainWindow : Window
    {
        List<System.Windows.Controls.TextBlock> randomBoxList = new List<System.Windows.Controls.TextBlock>();
    
        public MainWindow()
        {
            InitializeComponent();
            randomBoxList.Add(randomBoxOne);
            randomBoxList.Add(randomBoxTwo);
            randomBoxList.Add(randomBoxThree);
            randomBoxList.Add(randomBoxFour);
            randomBoxList.Add(randomBoxFive);
        }
    
        Random randomGenerator = new Random();
        int randomNumber;
    
        private void randomButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (System.Windows.Controls.TextBlock textBlock in randomBoxList)
            {
                randomNumber = randomGenerator.Next(1, 7);
                textBlock.Text = randomNumber.ToString();
            }
        }
    }