Reputation: 159
I have tried using a simple for loop:
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WPFGamesChess
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
Dispatcher.Invoke(makeGrid);
}
public void makeGrid()
{
Size s = new Size(20, 20);
for (int y = 0; y < s.Height; y++)
{
for (int x = 0; x < s.Width; x++)
{
Rectangle r = new Rectangle();
if ((x+y) % 2 == 0)
{
r.Fill = Brushes.Black;
}
else
{
r.Fill = Brushes.White;
}
r.Stroke = Brushes.Black;
r.StrokeThickness = 0;
double h = (RootGrid.Height / s.Height);
double w = (RootGrid.Width / s.Width);
r.Height = h;
r.Width = w;
r.Margin = new Thickness(0, 0, RootGrid.Width - r.Width - (x*w*2), RootGrid.Height - r.Height - (y*h*2));
RootGrid.Children.Add(r);
}
}
}
}
}
However, doing it this way prevents the display from loading as far as I can tell. I figured that this would need to be multi-threaded, but I can't figure out how to do that either. What I'm trying to do is make a grid for a chess board, but I'd like to be able to re-use that code for making a larger grid for a strategy game.
Upvotes: 1
Views: 426
Reputation: 16119
If you only need a few thousand objects...and most of them won't animate...then regular data-binding should handle that fine without tying up the GUI thread. Here's an example from an application I wrote in which each grid cell contains 17 different elements, that's almost 15,000 in total:
This is implemented with an ItemsControl using a Canvas as the panel and DataTemplating to select the types of elements to create. I don't notice any discernible pause at start-up, and real-time editing etc is perfectly smooth.
Also, since you specifically mentioned chess, here's an example of that I created earlier using the same technique, with the following result:
Upvotes: 2