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 codebehind, I add a stack panel to the 1st column, the second row to mainGrid, but I want the maximum stack panel width to be a column width of 1-50px. I came across accross stkPanel.Width = mainGrid.ColumnDefinitions(1).Width.ToString - 50 , however this will result in an error:

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 the way I want, or to install an add-on or similar?

Thanks,

Matt

+4
source share
4 answers

Turns out I was almost there. Instead of using

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

I had to use

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

+3
source

You have two properties for the Grid :

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

These two should do the trick, try

+4
source

When performing arithmetic on row and column size, you can work, you should know that there are pitfalls with this approach. When your data changes or the window size changes, the layout of the grid will be updated, and everything can change. Of course, you can adapt to these changes, but it works more.

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

+3
source

You must use ActualWidth and ActualHeight. For instance:

 stkPanel.Width = mainGrid.ColumnDefinitions[1].ActualWidth - 50; 
0
source

All Articles