yozawiratama
yozawiratama

Reputation: 4328

convert this UniformGrid xaml language to C#

Hi everyone i want to convert this xaml code to c# code please help me using a looping to save memory or line please help me

<UniformGrid Width="500" Height="500" x:Name="ChessBoard" VerticalAlignment="Center" HorizontalAlignment="Center">
        <Grid x:Name="Grid1" Background="Yellow" />
        <Grid x:Name="Grid2" Background="Black" />
        <Grid x:Name="Grid3" Background="Yellow" />
        <Grid x:Name="Grid4" Background="Black" />
        <Grid x:Name="Grid5" Background="Yellow" />
        <Grid x:Name="Grid6" Background="Black" />
        <Grid x:Name="Grid7" Background="Yellow" />
        <Grid x:Name="Grid8" Background="Black" />
        <Grid x:Name="Grid9" Background="Yellow" />
    </UniformGrid>

please

UniformGrid ChessBoard = new UniformGrid();
        ChessBoard.Width = 500;
        ChessBoard.Height = 500;
        ChessBoard.HorizontalAlignment = HorizontalAlignment.Center;
        ChessBoard.VerticalAlignment = VerticalAlignment.Center;
        Grid chressBox = new Grid();
        SolidColorBrush yell = new SolidColorBrush(Colors.Yellow);
        SolidColorBrush blk = new SolidColorBrush(Colors.Black);

        for (int ii = 1; ii <= 9; ii++)
        {
            if (ii % 2 == 0)
            {
                chressBox.Background = blk;
                chressBox.Name = "Grid" + ii.ToString();
                ChessBoard.Children.Add(chressBox);
            }
            else
            {
                chressBox.Background = yell;
                chressBox.Name = "Grid" + ii.ToString();
                ChessBoard.Children.Add(chressBox);
            }
        }
        LayoutRoot.Children.Add(ChessBoard);

itry to create that, but still wrong

Upvotes: 0

Views: 972

Answers (1)

Chris Taylor
Chris Taylor

Reputation: 53709

For a full chessboard you could do something like this

  Brush defaultBrush = new SolidColorBrush(Colors.Yellow);
  Brush alternateBrush = new SolidColorBrush(Colors.Black);

  for (int x = 0; x < 8; ++x)
  {
    for (int y = 0; y < 8; ++y)
    {
      Grid cell = new Grid();
      cell.Background = (y+x) % 2 == 0 ? defaultBrush : alternateBrush;
      ChessBoard.Children.Add(cell);
    }
  }

Here is a version with only a single for loop

  Brush defaultBrush = new SolidColorBrush(Colors.Yellow);
  Brush alternateBrush = new SolidColorBrush(Colors.Black);

  for (int i = 0; i < 64; ++i)
  {
    Grid cell = new Grid();
    cell.Background = (i + i / 8) % 2 == 0 ? defaultBrush : alternateBrush;
    ChessBoard.Children.Add(cell);
  }

This code assumes you have a ChessBoard defined as a UniformGrid as in your example.

Upvotes: 2

Related Questions