c# - 对象的 ActualHeight 和 ActualWidth 始终为零

标签 c# xaml windows-runtime actualwidth actualheight

我有一个带有 TextBlockCanvas,如下所示:

<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' s宽度大于 Canvas 宽度,会出现跑马灯动画:

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 应用商店应用,我希望它可以在不同的屏幕尺寸上进行缩放。

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

最佳答案

当调用 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。

关于c# - 对象的 ActualHeight 和 ActualWidth 始终为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12766891/

相关文章:

wpf - 如何在 WPF 应用程序中使用 Windows 8 运行时类 MediaCapture 来显示网络摄像头预览?

c# - Windows 8 - 如何更改动态平铺背景图像?

C# ASP.NET 应用程序正则表达式

c# - MySQL 连接器网络 6.9.9 设置向导提前结束

c# - T 上的泛型约束同时是引用类型和值类型?

c# - 带有自定义刻度的 slider (标签和速度)

c# - 导航转换 - Windows Phone 工具包

javascript - 共享魅力在使用几次后开始出现错误

c# - HTML 到格式化文本 C#

wpf - 在DataGrid列中设置DatePicker的默认值