【问题标题】:ActualHeight and ActualWidth of object is always zero对象的 ActualHeight 和 ActualWidth 始终为零
【发布时间】:2012-10-07 07:19:14
【问题描述】:

我有一个Canvas 和一个TextBlock,如下所示:

<Canvas x:Name="ContentPanel" Grid.Row="1" DoubleTapped="ContentPanel_DoubleTapped">
        <TextBlock x:Name="WordBlock" FontSize="226.667" FontFamily="Segoe UI Semilight" TextAlignment="Center"
                   RenderTransformOrigin="0.5, 0.5">
            <TextBlock.RenderTransform>
                <TranslateTransform x:Name="translate"/>
            </TextBlock.RenderTransform>
        </TextBlock>
    </Canvas>

我的应用是这样的,当用户导航到这个页面时,TextBlock 将在Canvas 中居中,如果TextBlock 的宽度大于画布的宽度,则会出现选取框动画:

private void SetAnimation()
{
    Canvas.SetLeft(WordBlock, (ContentPanel.ActualWidth - WordBlock.ActualWidth) / 2);
    Canvas.SetTop(WordBlock, (ContentPanel.ActualHeight - WordBlock.ActualHeight) / 2);

    if (WordBlock.ActualWidth > ContentPanel.ActualWidth)
    {
        MarqueeAnimation.From = WordBlock.ActualWidth;
        MarqueeAnimation.To = -WordBlock.ActualWidth;
        MarqueeAnimation.Duration = new Duration(new TimeSpan(0, 0, 10));
        MarqueeBoard.Begin();
    }
}

此方法称为 OnNavigatedTo。我不知道为什么TextBlock 不会居中,因为ActualHeightActualWidth 属性总是返回为0.0。我不想设置固定尺寸,因为这是一个 Windows 应用商店应用,并且希望它能够跨不同的屏幕尺寸进行缩放。

有什么想法吗?我被卡住了。

【问题讨论】:

  • 如何设置 WordBlock 的文本?
  • 在上一页中,将 TextBox 的内容作为导航参数传递,然后从 OnNavigatedTo 中检索。

标签: c# xaml windows-runtime actualwidth actualheight


【解决方案1】:

当 OnNavigatedTo 被调用时,我不相信页面实际上已经被绘制了。在尝试调整大小和重新排列事物时,我也有类似的困惑。答案似乎是等到页面加载完毕后再进行计算:

public ChallengePage()
{
  this.InitializeComponent();
  this.Loaded += ChallengePage_Loaded;
}

void ChallengePage_Loaded(object sender, RoutedEventArgs e)
{
  *Do your calculations which use ActualWidth and ActualHeight in here*
}

我相信你会需要这样的东西。将 Loaded 处理程序添加到页面的初始化中,然后您可以从那里调用 SetAnimation。

【讨论】:

  • 所以我将使用 OnNavigatedTo 检索我传递到此页面的单词并将其设置为 WordBlock 的值,然后在 Loaded 上调整大小并重新排列所有内容?
  • 是的,在导航时更改文本,让页面加载以便它实际呈现对象,然后它们应该具有大小,以便您可以在加载时重新排列:o)跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多