Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get actual WPF Grid Width

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

like image 333
Lima Avatar asked May 04 '11 03:05

Lima


4 Answers

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

like image 63
Damascus Avatar answered Oct 13 '22 04:10

Damascus


Turns out I was almost there. Instead of using

stkPanel.Width = mainGrid.ColumnDefinitions[1].Width.ToString - 50

I should have used

stkPanel.Width = mainGrid.ColumnDefinitions[1].ActualWidth.ToString - 50

like image 34
Lima Avatar answered Oct 13 '22 03:10

Lima


While doing row and column size arithmetic yourself can work, you should be aware there are pitfalls with this approach. When your data changes or the window is resized the grid's layout will be updated and everything can change. Of course you can adapt to these changes but that's more work.

Instead, if you can, you might try to do everything with the grid itself using an additional column and column spanning. Then the grid will take care of all the dirty work and you can focus on the appearance.

like image 35
Rick Sladkey Avatar answered Oct 13 '22 03:10

Rick Sladkey


You must use ActualWidth and ActualHeight. For example:

stkPanel.Width = mainGrid.ColumnDefinitions[1].ActualWidth - 50;
like image 22
ste Avatar answered Oct 13 '22 02:10

ste