【问题标题】:FrameworkElement.ActualHeight { get; } always giving 0FrameworkElement.ActualHeight { 得到; } 总是给 0
【发布时间】:2020-11-23 22:44:41
【问题描述】:

这是我的 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。我尝试设置 topRectangle.Height 而不是 ActualHeight,结果是:

高度:NaN

实际高度:NaN

如果代码中不清楚,gridrectangle的高度不为0

有答案吗?

【问题讨论】:

  • 您将 Grid 维度设置为 Auto,但将其一些内容维度绑定到父级。

标签: c# xaml computer-science actualheight


【解决方案1】:

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

<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>

【讨论】:

  • 保持不变。还有其他想法吗?
  • @RafaelBradley 你什么时候设置标签内容?在布局测量事件之前?
猜你喜欢
  • 2020-04-17
  • 1970-01-01
  • 2018-12-23
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多