2012-11-27 31 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