【问题标题】:Why is my Grid's width NaN?为什么我的 Grid 的宽度是 NaN?
【发布时间】:2014-04-04 09:41:49
【问题描述】:

我在视图中有以下标记。当我在视图的启动代码期间收到WindowContainer.Width 时,它返回NaN

<Border BorderThickness="10">
  <StackPanel x:Name="Panel" Orientation="Vertical" >
    <Grid x:Name="WindowContainer" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Loaded="WindowContainer_OnLoaded">
      <delphi:Win32WindowHost x:Name="Host" />
    </Grid>
    <TextBlock x:Name="InfoTextBlock" HorizontalAlignment="Right" />
  </StackPanel>
</Border>

Stretch 是否使网格拉伸以容纳其所有内容或填充其容器?我希望它拉伸以填充容器 Border,并具有适当的 double 宽度,我可以使用它来调整浮动窗口的大小以使其大小相同。

【问题讨论】:

  • Double.NaN 只是Width 属性的默认值。这意味着没有明确设置宽度。您应该始终使用ActualWidth 属性来获取元素的实际宽度。

标签: wpf wpf-controls wpf-4.0


【解决方案1】:

Does Stretch make the grid stretch to accomodate all its content, or to fill its container?

来自MSDN关于HorizontalAlignment="Stretch"

子元素被拉伸以填充父元素分配的布局空间。显式 WidthHeight 值优先。


Why is my Grid's width NaN?

NaN 表示“未设置”。 FrameworkElement 是 WPF 中许多控件的基类,如果您没有显式设置 Height 和 Width 属性,则类构造函数中的默认值将是 NaN


When I get WindowContainer.Width during start-up code for the view, it returns NaN

在这种情况下,尝试获取ActualWidth,而不是Width,因为:

ActualWidth 属性是基于其他宽度输入和布局系统的计算 值。该值由布局系统本身根据实际渲染过程设置,因此可能会稍微落后于作为输入更改基础的 Width 等属性的设置值。

【讨论】:

  • 我在网格的 OnInitialized 事件中得到 0.0。我应该稍后在视图启动中获取值吗?
  • @ProfK:是的,例如尝试在Loaded="WindowContainer_OnLoaded" 中获取这些值。
  • 在这种情况下,我得到了 ActualWidth 的正确值,但 ActualHeight 仍然返回 0.0
  • @ProfK:对我来说效果很好。对于WindowContainer ActualHeight==高度为 400。
  • 抱歉,我在代码示例中留下了明确的 Height 属性。它现在已在我的代码和示例中删除。网格不应该拉伸以填充边框,它围绕控件的外部并在其中具有高度?
猜你喜欢
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
  • 2014-09-23
  • 2019-12-26
相关资源
最近更新 更多