Writing games in WPF (programatically creating a grid)

Hello Everyone,
I’m working with a friend of mine on a tetris clone using WCF and realized that its really fun. It takes a bit to wrap your head around the proper way of using XAML but after that it’s pretty smoth. Also the layout tools on Visual Studio 2008 are pretty wicked they pretty much read your code to generate previes as long as you have a default constructor with some default settings. I will be posting screenshot to the game once it’s done but i wanted to explain something that many people might found useful.

Programatically creating a grid the way i do it.

  • First go to the xaml and place the grid were you want it to be and set the size to it.
  • Second since you want to set columns and rows by yourself write code similar to this one for your objects:
    //MainGrid is the name i gave in the XAML to my grid.
    MainGrid.RowDefinitions.Add(new RowDefinition());//Adds a new row to the Grid
    MainGrid.ColumnDefinitions.Add(new ColumnDefinition()); // adds a new column
  • Step 3 set the objects that you wish to have in each of the places you created on the layout
    Rectangle tmp = new Rectangle(); //Creates rectangle
    tmp.Width = 20;
    tmp.Height = 20;
    tmp.Stroke = Brushes.Black;
    Grid.SetColumn(tmp , 0);
    Grid.SetRow(tmp , 0);
    MainGrid.Children.Add(tmp); //Adds rectangle to grid on position 0
  • This can be done with any type of UIElement object. I will be sure to post at least screenshots of the tetris clone when we finish it. Expect Soon a post on how to go about creating and using your own user components in WPF.


    2 thoughts on “Writing games in WPF (programatically creating a grid)

    Leave a Reply