-1

这是我的 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

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

有什么答案吗?

4

1 回答 1

1

设置HorizontalAlignmentStretch而不是将其宽度绑定到其父容器,该容器由于 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>
于 2020-08-03T20:45:40.437 回答