2012-11-27 40 views
1

一個UniformGrid在C#我是比較新的C#和我試圖創建一個窗口與相同尺寸的正方形的動態量的網格。正方形然後通過一個過程改變它們的顏色。繪畫使用WPF

我正在努力產生正方形的網格。每當我運行這個應用程序時,它似乎都會在資源上瘋狂,我不知道爲什麼。

我使用的代碼如下:

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


     } 
    } 
} 

這甚至我想借此如果我想正方形的修改網格的方法呢?

感謝您的幫助,

傑森

+1

爲什麼不使用WPF均勻網格? –

+0

100 * 100 = 10000 GDI一次處理,難怪這是忙碌=) –

+0

@ SebastianEdelmeier GDI!?!?!這是WPF不蹩腳的winforms。 –

回答

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

非常好,很好,謝謝。 – xyzjace