0

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?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Daybreak
  • 3
  • 2
  • `Grid` isn't really intended for that. Regardless, what was wrong with your attempt? – BradleyDotNET Dec 16 '14 at 19:15
  • @BradleyDotNET: Which XAML control is better suited? – Robert Harvey Dec 16 '14 at 19:16
  • @RobertHarvey For dynamic layout? `StackPanel` for one. The only thing `Grid` buys you here is the even spacing, which you *can* write a custom panel for. It mostly depends on what he is *actually* trying to accomplish. – BradleyDotNET Dec 16 '14 at 19:18
  • @BradleyDotNET i want the layout to change i.e from 3x3 to a 4x4 so somehow i need to set this xaml line '' in c# code in my class that i get the same result. – Daybreak Dec 16 '14 at 19:23
  • 1
    Couldn't you just add a `ColumnDefinition` object to the collection? I still don't understand what is going wrong with your attempt (regardless of whether or not its the correct approach) – BradleyDotNET Dec 16 '14 at 19:24
  • @BradleyDotNET maybe my approach wasn't wrong, it's only i don't know how to write the proper line of code to add the object to the collection. – Daybreak Dec 16 '14 at 19:29

1 Answers1

1

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

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260