簡體   English   中英

使用WPF在C#中繪制UniformGrid

[英]Painting a UniformGrid in C# using WPF

我是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);


        }
    }
}

如果我想要可修改的正方形網格,這甚至是我想采用的方法嗎?

謝謝你的幫助,

傑森

這似乎執行得很快

   <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) });
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM