将此UniformGrid xaml语言转换为c#
本文关键字:转换 语言 UniformGrid xaml 将此 | 更新日期: 2023-09-27 17:53:00
大家好,我想把这个xaml代码转换成c#代码请帮助我使用循环来节省内存或行请帮帮我
<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>
请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);
尝试创建,但仍然错误
对于一个完整的棋盘,你可以这样做
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);
}
}
这个版本只有一个for循环
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);
}
此代码假设您有一个定义为UniformGrid的ChessBoard
,如您的示例。