Page 1 of 1

Get Grid.ColumnDefinition width

Posted: 25 Jan 2019, 16:01
by realesmedia
Hi

How to find the width of a Grid.ColumnDefinition in pixels if in xaml <ColumnDefinition Width = "Auto"/> or <ColumnDefinition Width = "*"/>

all methods ColumnDefinition return 0.0f

ColumnDefinition :: GetActualWidth ()
ColumnDefinition :: GetWidth ()
ColumnDefinition :: GetRenderSize ()

Re: Get Grid.ColumnDefinition width

Posted: 28 Jan 2019, 11:41
by sfernandez
To get the actual width (or height) of a Grid's column (row) you have to place an element in that cell and ask for its ActualWidth (ActualHeight). Columns (Rows) are not measured, only the elements inside the Grid, using the information from Column and Row definitions.
<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"/>
    <ColumnDefinition Width="*"/>
  </Grid.ColumnDefinitions>
  <Decorator x:Name="FirstColumnRef" Grid.Column="0"/>
  ...
</Grid>
Loaded += (s, e) =>
{
  FrameworkElement firstColumnRef = (FrameworkElement)FindName("FirstColumnRef");
  Console.WriteLine("FirstColumnRef.ActualWidth = " + firstColumnRef.ActualWidth);
};

Re: Get Grid.ColumnDefinition width

Posted: 29 Jan 2019, 12:51
by realesmedia
In this case:
    <Grid Background="Red">
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.5*"/>
        <ColumnDefinition Width="6"/>
        <ColumnDefinition Width="0.5*"/>
      </Grid.ColumnDefinitions>
        <Grid Grid.Column="1" Background="Black"/>
    </Grid>
    
    auto w = Grid::GetColumnDefinitions()->Get(0)->GetActualWidth();  // 0.f ???

Re: Get Grid.ColumnDefinition width

Posted: 29 Jan 2019, 16:23
by sfernandez
If you have this Grid and want to know the size of the first column, then you have to place an (invisible) element in that column:
<Grid Background="Red">
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="0.5*"/>
    <ColumnDefinition Width="6"/>
    <ColumnDefinition Width="0.5*"/>
  </Grid.ColumnDefinitions>
  <Decorator x:Name="FirstColumnRef" Grid.Column="0"/>
  <Grid Grid.Column="1" Background="Black"/>
</Grid>
And in code you would look for that element after layout has finished:
Loaded() += [](BaseComponent* sender, const RoutedEventArgs& e)
{
  FrameworkElement* firstColumnRef = FindName<FrameworkElement>("FirstColumnRef");
  m_firstColumnWidth = firstColumnRef->GetActualWidth();
};

Re: Get Grid.ColumnDefinition width

Posted: 29 Jan 2019, 17:58
by realesmedia
Thanks

Re: Get Grid.ColumnDefinition width

Posted: 01 Feb 2019, 14:21
by jsantos
Marking as solved!