I'm currently creating a connect-4 game in order to learn WPF & XAML. I made the UI but I'm stuck on a problem.
Below you can see an extract of the XAML code concerning the board of the game :
<Grid DockPanel.Dock="Bottom" Background="#FF1506A4" MouseLeftButtonUp="Grid_MouseLeftButtonUp_1">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
... 5 more rows
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
... 6 more columns
</Grid.ColumnDefinitions>
<Ellipse Grid.Row="0" Grid.Column="0" Fill="White" Margin="8"/>
... 41 more ellipses
</Grid>
The board is stored in an array of Token (an enumeration with Empty, Red and Yellow) in the class GameState.
The colors of the Ellipses are provided using the class SolidBrushColor.
My problem is that I don't know how to change the color of the ellipses according to the game model.
I guess I should use data binding but I have to convert colors from the type Token to the type SolidBrushColor before binding the data. I think it could be achieved using some DataObjectProvider objects but it seems over complicated to create 42 DataObjectProvider objects for such a simple task...
So what would be the correct solution according to the best pratices ?
You'll want to use some sort of ViewModel at the backend, and then leverage DataBinding.
Assuming the following (contrived) ViewModel structure that represents a Connect Four board.
BoardViewModel.cs
SquareViewModel.cs
Then you can use the following XAML to represent your board.
MainWindow.xaml
The important things to note are:
At run-time, you will want to set the DataContext of your board View to a real instance of the BoardViewModel (or whatever your ViewModel is called), but the basic idea of how to change the colour of the tokens is present.