Ralfs R
Ralfs R

Reputation: 77

How do you create box for each element of array automatically in xaml?

I've been wondering - how do you create box for each element of array automatically in xaml? Lets say my code has an array that contains 99 elements in total, i want each element to contain this little 50px*50px box. Of course i don't think the right way would be to create 99 additional small boxes and assign them to array.

So far i have looked into databinding and ItemsControl, but can't find a good enough example for me to follow.

 string[] assignments = new string[] { "A", "B", "C", "D", "E", "F" };
 Random rnd = new Random();
 string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();

 string repeatNumber = "";

 for (int i = 1; i < 100; i++)
 {
      if (i == 9)
      {
         repeatNumber = randomingArray[i % randomingArray.Length];
         Console.WriteLine(repeatNumber);

      }
      else if ((i % 9) == 0)
      {
         Console.WriteLine(repeatNumber);
      }
      else
      {
         Console.WriteLine(randomingArray[i % randomingArray.Length]);
      }

 }

How do i do this?

Upvotes: 0

Views: 479

Answers (1)

Ayyappan Subramanian
Ayyappan Subramanian

Reputation: 5366

I would say try more basic WPF tutorials. I would recommend to see some MVVM tutorial as well. For now see below code.

<Grid>       
    <ListBox x:Name="ItemsControl1" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Aqua" BorderThickness="2" Width="Auto" Height="Auto" >
                    <TextBlock Text="{Binding}" Margin="10"/>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ItemsControl1.ItemsSource = new string[] { "A", "B", "C", "D" };
    }
}

Upvotes: 1

Related Questions