简体   繁体   English

Windows Phone 8.1运行时应用程序无法获取TextBlock ActualWidth值

[英]cannot get TextBlock ActualWidth value in windows phone 8.1 runtime app

I'm developing wp8.1 runtime app.I need to get a textblock control's actual width to do something before a page(or an usercontrol) loaded. 我正在开发wp8.1运行时应用程序,我需要获取文本块控件的实际宽度才能在加载页面(或用户控件)之前执行某些操作。 In the wp8 app, I can do this with using the code: 在wp8应用中,我可以使用以下代码执行此操作:

 var textBlock = new TextBlock();
 textBlock.FontSize = 26;
 textBlock.Text = "A";
 var width = textBlock.ActualWidth;

but, in the wp8.1 runtime app, the code above cannot get actual width, and it always returns 0. Could someone tell me how to get textblock actual width before page loaded in wp8.1 runtime app? 但是,在wp8.1运行时应用程序中,以上代码无法获取实际宽度,并且始终返回0。有人可以告诉我如何在将页面加载到wp8.1运行时应用程序中之前获取textblock实际宽度吗?

Thanks! 谢谢!

I'm actually surprise it worked in WP8.0 SL so I did a little test. 我真的很惊讶它可以在WP8.0 SL中工作,所以我做了一些测试。 You're right it does work. 没错,它确实有效。 To get it to work in WP8.1 runtime, I would add it to a Container then call UpdateLayout like below: 为了使其能够在WP8.1运行时中工作,我将其添加到Container中,然后按如下所示调用UpdateLayout


<Grid x:Name="ContentPanel">
    <!--- content xaml --->
</Grid>
private void Page_Loaded(object sender, RoutedEventArgs e)
{
    TextBlock tb = new TextBlock();
    tb.Margin = new Thickness(-2500, -2500, 0, 0);  // hide it using margin
    tb.FontSize = 26;
    tb.Text = "Test Test Test Test";
    this.ContentPanel.Children.Add(tb);
    tb.UpdateLayout();

    var tb_width  = tb.ActualWidth;
    var tb_height = tb.ActualHeight;
}

I don't think you can get it before the TextBlock is actually loaded. 我不认为您可以在实际加载TextBlock之前得到它。

The thing is that the default value of ActualWidth is 0 and the default value is what you would get if the TextBlock has not yet been loaded or rendered in the UI. 事实是,ActualWidth的默认值为0,而默认值是如果尚未在UI中加载或渲染TextBlock时将获得的默认值。 Reference and more details about this property can be found here . 有关此属性的参考和更多详细信息,请参见此处

You might be able to catch a SizeChanged event of the TextBlock and do something from there. 您也许可以捕获TextBlock的SizeChanged事件,然后从那里进行一些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM