How do I bind to a RowDefinition's height?

2019-05-10 23:31发布

问题:

In this example code, I'm trying to offset the Grid's Canvas position by the height of one of its rows. Does anyone see what I might be doing wrong? As you can see, I tried moving the binding lower in the xaml file, just in case the RowDefinitions needed to be defined first. Either way, it doesn't seem to matter because Canvas.Top is always 0.

<Canvas>
   <Grid Canvas.Top="{Binding ElementName=DetailsRow, Path=ActualHeight}">
      <Grid.RowDefinitions>
         <RowDefinition x:Name="NameRow" />
         <RowDefinition x:Name="DetailsRow" />
      </Grid.RowDefinitions>
      <Button Grid.Row="0">Button</Button>
      <Button Grid.Row="1">Button</Button>

      <!-- I expected this to maybe work, but no dice
      <Canvas.Top>
         <Binding ElementName="DetailsRow" Path="ActualHeight" />
      </Canvas.Top>
      -->

   </Grid>
</Canvas>

回答1:

ActualHeight is not a dependency property so it's probably not triggering any kind of change notification. ActualHeight actually starts at 0 until the grid is measured so that could be one explanation. Unlike FrameworkElement, which does define ActualHeight as a dependency property, RowDefinition doesn't derive from FrameworkElement and just defines ActualHeight as a normal property with no change event.

I've actually thought about the fact that there should be a BindingMode.Polling option where the binding system would poll the source property at certain intervals. But unfortunately you may just be stuck doing it in code.