Why there is exception on grid creation

179 views Asked by At

I have to create a grid array the size of this array is determined dynamically.

My try to do this is:

int size = 4; //This "size" will be determined dynamically.suppose i got 4 here
Grid[] rowgrid = new Grid[size];
for (int i = 0; i < size; i++)
{
    rowgrid[i].RowDefinitions.Add(new RowDefinition());
}

It don't give any error but when i run it gives exception : The object reference is not set to an instance of an object.

EDIT: I want to use array because : after intializing before i have to do like this :

rowgrid[0].Opacity=0.1;
rowgrid[1].Opacity=0.3;
rowgrid[2].Opacity=0.5;

If you suggest me not work programatically then i want to inform in avance that i know that well but i am obliged to do this because i am working in already developed project and no more options are there. It would be a big help if some one bring me to come out of this error or any other alternative to achieve this.

1

There are 1 answers

3
CampDev On

If you want a Grid with differents Rows or Columns. You can use UniformGrid, columns and rows properties are binding.

So,

<UniformGrid Name="uniformGrid1" Rows="{Binding NumberOfRows}" Columns="{Binding NumberOfColumns}">
    <Button Content="Button1" Grid.Row="0" Grid.Column="0" />
    <Button Content="Button2" Grid.Row="0" Grid.Column="2" />
</UniformGrid>

In your code

private int _numberOfRows;
public int NumberOfRows
    {
        get { return _numberOfRows; }
        set { _numberOfRows= value; RaisePropertyChanged("NumberOfRows"); }
    }    
private int _numberOfColumns;
public int NumberOfColumns
    {
        get { return _numberOfColumns; }
        set { _numberOfColumns= value; RaisePropertyChanged("NumberOfColumns"); }
    } 


public MainViewModel()
{
    NumberOfColumns = 3;
    NumberOfRows = 2;
}