Skip to content

Instantly share code, notes, and snippets.

@DraconicDragon
Last active October 8, 2023 14:08
Show Gist options
  • Select an option

  • Save DraconicDragon/6ae2071665343a229a7ba13a7f3536c1 to your computer and use it in GitHub Desktop.

Select an option

Save DraconicDragon/6ae2071665343a229a7ba13a7f3536c1 to your computer and use it in GitHub Desktop.
XAML Chessboard with Gridview, ItemsPanel, ItemsTemplate

XAML Chessboard with Gridview, ItemsPanel, ItemsTemplate

XAML

<GridView
    Width="Auto"
    Height="Auto"
    ItemsSource="{x:Bind Chessboard}">
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid MaximumRowsOrColumns="8" Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="local:ChessSquare" >
            <Border
                Width="80"
                Height="80"
                Background="{x:Bind Color}"
                Tapped="Cell_Click">
                <TextBlock
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Foreground="Black"
                    Text="{x:Bind Text}" />
            </Border>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

C# code behind

public sealed partial class MainPage : Page
{
    public List<ChessSquare> Chessboard { get; set; }
    public Color WhiteColor { get; set; } = Colors.White;
    public Color BlackColor { get; set; } = Colors.DimGray;

    public MainPage()
    {
        this.InitializeComponent();
        InitializeChessboard();
        DataContext = this;
    }

    private void InitializeChessboard()
    {
        Chessboard = new List<ChessSquare>();

        for (int row = 0; row < 8; row++)
        {
            for (int col = 0; col < 8; col++)
            {
                var color = (row + col) % 2 == 0 ? WhiteColor : BlackColor;
                var rank = 8 - row; // Rank (row) number
                var file = (char)('a' + col); // File (column) letter
                var text = $"{file}{rank}";
                Chessboard.Add(new ChessSquare { Color = new SolidColorBrush(color), Text = text });
            }
        }
    }

public class ChessSquare
{
    public SolidColorBrush Color { get; set; }
    public string Text { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment