FrameworkElement.ActualHeight{get;}总是给出0



这是我的c#代码:

double height = grid.ActualHeight;
double newHeight = height - rectangle.ActualHeight;
topRectangle.Height = newHeight;
label.Content = "height: " + height + "nNew Height: " + newHeight;

xaml文件是这样的:

<Grid x:Name="grid" Height="Auto" Width="Auto">
<Rectangle x:Name="rectangle" Fill="#FF181818" HorizontalAlignment="Left" Height="222" Margin="0,0,-0.333,0" Stroke="#FF181818" VerticalAlignment="Bottom" Width="{Binding ActualWidth, ElementName=grid}"/>
<Rectangle x:Name="topRectangle" Fill="#FF181818" HorizontalAlignment="Left" Height="285" Margin="0,0,0,221.667" Stroke="#FF181818" VerticalAlignment="Bottom" Width="190"/>
<Label x:Name="label"  Content="Label" HorizontalAlignment="Left" Margin="306,99,0,0" VerticalAlignment="Top" Foreground="White"/>
</Grid>

运行时标签的文本如下:

高度:0

新高度:0

但我尝试了更多,这总是给出0,因为高度为0,所以看不到顶部矩形。我试着设置topRectangle.Height而不是ActualHeight,结果是:

高度:NaN

实际高度:NaN

如果代码中不清楚,网格矩形的高度不是0

有答案吗?

HorizontalAlignment设置为Stretch,而不是将其宽度绑定到其父容器,后者由于Auto而需要测量其内容。

<Grid x:Name="grid" Height="Auto" Width="Auto">
<Rectangle x:Name="rectangle" Fill="#FF181818" HorizontalAlignment="Stretch" Height="222" Margin="0,0,-0.333,0" Stroke="#FF181818" VerticalAlignment="Bottom"/>
<Rectangle x:Name="topRectangle" Fill="#FF181818" HorizontalAlignment="Left" Height="285" Margin="0,0,0,221.667" Stroke="#FF181818" VerticalAlignment="Bottom" Width="190"/>
<Label x:Name="label"  Content="Label" HorizontalAlignment="Left" Margin="306,99,0,0" VerticalAlignment="Top" Foreground="White"/>
</Grid>

最新更新