Reputation: 183
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. In the wp8 app, I can do this with using the code:
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?
Thanks!
Upvotes: 1
Views: 637
Reputation: 8161
I'm actually surprise it worked in WP8.0 SL so I did a little test. 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:
<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;
}
Upvotes: 1
Reputation: 15006
I don't think you can get it before the TextBlock is actually loaded.
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. 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.
Upvotes: 0