Get actual WPF Grid Width

Lima picture Lima · May 4, 2011 · Viewed 13.7k times · Source

I have a WPF Window with a grid:

<Grid Name="mainGrid">
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="20*" />
    <ColumnDefinition Width="700*" />
    <ColumnDefinition Width="190*" />
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition Height="80" />
    <RowDefinition Height="220*" />
    <RowDefinition Height="450*" />
    <RowDefinition Height="160*" />
    <RowDefinition Height="30" />
  </Grid.RowDefinitions>
</Grid>

In the codebehind, I am adding a stackpanel to the 1st column, 2nd row of mainGrid, but I am wanting the max width of the stackpanel to be the width of column 1 - 50px. I stumbled accross stkPanel.Width = mainGrid.ColumnDefinitions(1).Width.ToString - 50, however this will error with:

700* cannot be converted to double

Is there a way to get the actual width of the grid column as it appears on the screen to use how I am wanting, or do I set padding or similar?

Thanks,

Matt

Answer

Damascus picture Damascus · May 4, 2011

You have two properties for a Grid :

Grid g = new Grid();
double width1 = g.ActualWidth;
double width2 = g.RenderSize.Width;

These two should do the trick, try it