1

我对 C# 比较陌生,我正在尝试创建一个带有动态数量的相同大小正方形网格的窗口。然后这些方块将通过一个过程改变它们的颜色。

我目前正在努力生成正方形网格。每当我运行该应用程序时,它似乎都在消耗资源,我不知道为什么。

我使用的代码如下:

private void Window_Loaded(object sender, RoutedEventArgs e) {


    //create a blue brush
    SolidColorBrush vBrush = new SolidColorBrush(Colors.Blue); 

    //set the columns and rows to 100
    cellularGrid.Columns = mCellAutomaton.GAME_COLUMNS; 
    cellularGrid.Rows = mCellAutomaton.GAME_ROWS;

    //change the background of the cellular grid to yellow
    cellularGrid.Background = Brushes.Yellow;

    //create 100*100 blue rectangles to fill the cellular grid
    for (int i = 0; i < mCellAutomaton.GAME_COLUMNS; i++) {
        for (int j = 0; j < mCellAutomaton.GAME_ROWS; j++) {

            Rectangle vRectangle = new Rectangle();

            vRectangle.Width = 10;
            vRectangle.Height = 10;
            vRectangle.Fill = vBrush;

            cellularGrid.Children.Add(vRectangle);


        }
    }
}

如果我想要一个可修改的正方形网格,这甚至是我想要采取的方法吗?

谢谢你的帮助,

杰森

4

1 回答 1

0

这似乎执行得很快

   <Window x:Class="WpfApplication6.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="350" Name="UI">
        <Grid Name="Test">
            <UniformGrid Name="UniGrid" />
        </Grid>
    </Window>


/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        AddRows(new Size(10, 10));
    }

    private void AddRows(Size recSize)
    {
        UniGrid.Columns = (int)(UniGrid.ActualWidth / recSize.Width);
        UniGrid.Rows = (int)(UniGrid.ActualHeight / recSize.Height);
        for (int i = 0; i < UniGrid.Columns * UniGrid.Rows; i++)
        {
            UniGrid.Children.Add(new Rectangle { Fill = new SolidColorBrush(Colors.Yellow), Margin = new Thickness(1) });
        }
    }
}
于 2012-11-27T09:28:30.080 回答