NomenNescio
NomenNescio

Reputation: 3030

Get current column width and height programmatically?

I'm trying to get the width and the height of a grid programmatically, In a UserControl.

Here is my XAML grid:

<Grid Name="BallGrid" Background="DarkBlue" Height="auto" Width="auto">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
</Grid>

But both of these:

double width = BallGrid.ColumnDefinitions[0].ActualWidth;
double height = BallGrid.RowDefinitions[0].ActualHeight;

return 0,

and these

double width = BallGrid.ColumnDefinitions[0].Width.Value;
double height = BallGrid.RowDefinitions[0].Height.Value;

return both return 1.

I'd like to know the actual width, preferably in the same units as margin sizes. How can I get these values programmatically?

The column values are queried in a ProgessChanged method, that is called by a BackgroundWorker every 50 ms, maybe that makes a difference.

Upvotes: 2

Views: 4992

Answers (3)

Tergiver
Tergiver

Reputation: 14517

They are valid after the source has been Initialized. You can override OnSourceInitialized to know when that has occurred.

Upvotes: 1

brunnerh
brunnerh

Reputation: 185290

Usually you use ActualWidth/Height, here those properties are a bit lazy:

When you add or remove rows or columns, the ActualWidth for all ColumnDefinition elements and the ActualHeight of all RowDefinition elements becomes zero until Measure is called.

So you could probably call Measure manually or try to wait for it.

Upvotes: 4

Tejas Sharma
Tejas Sharma

Reputation: 3440

try BallGrid.RenderSize.Height and BallGrid.RenderSize.Width

Upvotes: 0

Related Questions