Daybreak
Daybreak

Reputation: 3

I need my WPF grid control to be dynamically sizable (more or less rows and columns)

i want to have the grid layout dynamic. pretty much the only modification needed is that i need sometimes more and less rows and columns. So the thing is, how do i access the row- & columndefinition in my c# class?

<StackPanel Grid.Row="1" VerticalAlignment="Stretch">
  <Grid Name="mygrid" Height="490">
    <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="*"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
  </Grid>
</StackPanel>

Though with c# i am not getting to any solution. I tried with this attempt, though came to no conclusion

mygrid.ColumnDefinitions

Can somebody point me into the right direction?

Upvotes: 0

Views: 891

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

It should be straightforward to change the column definitions. ColumnDefinitionCollection implements IList<ColumnDefinition>, so you can treat it like normal lists in .Net.

Add:

var newColumn = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
mygrid.ColumnDefinitions.Add(newColumn);

Remove:

mygrid.ColumnDefinitions.RemoveAt(mygrid.ColumnDefinitions.Count - 1);

(Note: you might also want to consider using an attached property to bind the number of rows/columns -- see here for example.)

Upvotes: 1

Related Questions