How can I create board for simple game, looks like for chess,but user could dynamically change number of column and rows? In cells I could insert symbol of pawn, like small image or just ellipse or rectangle with fill. This board should have possibility add and remove pawn from cells and move pown from one cell to another.
My first idea was Grid. I do it in code behind, but it’s hurt to implement events or everything in runtime create board :/
int size = 12;
Grid board = new Grid();
board.ShowGridLines = true;
for (int i = 0; i < size;i++ )
{
board.ColumnDefinitions.Add(new ColumnDefinition());
board.RowDefinitions.Add(new RowDefinition());
}
//komputer
Rectangle ai = new Rectangle();
ai.Height = 20;
ai.Width = 20;
ai.AllowDrop = true;
ai.Fill = Brushes.Orange;
Grid.SetRow(ai, 0);
Grid.SetColumn(ai,0);
//człowiek
Rectangle hum = new Rectangle();
hum.Height = 20;
hum.Width = 20;
hum.AllowDrop = true;
hum.Fill = Brushes.Green;
Grid.SetRow(hum,size);
Grid.SetColumn(hum,size);
board.Children.Add(ai);
board.Children.Add(hum);
this.Content = board;
- It’s a way to do this dynamically col and row change in XAML ?
- It’s better way to implement that board create and implement events on move pawn from one cell to another ?
You’ll still have to use code-behind to change the
RowDefinitionsandColumnDefinitionsproperties of theGridin this example, since they’re not dependency properties. But all the rest of the logic can be handled in the view model class.The XAML:
The
Piececlass – obviously you’ll need to implementINotifyPropertyChangedon theRowandColumnproperties to handle moving pieces about.Populating the board:
I’ve used an
ItemsControlto contain the pieces in this example. You could use aListBoxinstead – that’s kind of nice because it gives you item selection for free. Note that if you do this you’ll have to change theStyle‘sTargetTypetoListBoxItem, since that’s what theListBoxwraps its item elements in instead ofContentPresenter.Edit:
I wrote this answer quite a while ago, and it’s got a problem.
Assigning the
Grid.RowandGrid.Columnproperties using a style that’s applied to the item container generated by the grid is right. Figuring out that the item container is aContentPresenterand creating a default style for that type is not. (It’ll work reliably in this case, but there are lots of cases where it won’t.)You should still create a style, but it should be assigned to the
ItemsControl‘sItemContainerStyle. This style’s automatically applied to whatever container element the control generates for its items – so if theItemsControlyou’re using is aListBox, it will apply it to theListBoxItem, and if it’s aTabControl, it’ll get applied to theTabItem, and so on.