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
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
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
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.
You must use ActualWidth and ActualHeight. For example:
stkPanel.Width = mainGrid.ColumnDefinitions[1].ActualWidth - 50;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With