gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:02:20 25 4
gpt4 key购买 nike

我有一个带有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com