在windows8 metro中计算TextBox的实际宽度ActualWidth


                TextBlock block = new TextBlock();
                block.Text = "hello";
                Size size = new Size(1024, 1024);
                block.Measure(size);
                Canvas.SetLeft(block, leftMargin - block.ActualWidth);

借鉴1:可惜rect方法我试了下ActualWidth还是0.0

在windows8 metro/windows phone中计算字的宽度

在windows 8和windows phone中有地方我们需要计算字的宽度,例如在显示的时候需要截取多余的字变成...,还有在数据排版上面这个也是必不可少的。

一个字符显示的像素宽度与字体和字体大小有关系。我用到的是一个比较笨拙的方法,那就是拿textblock去量。

具体如下:

TextBlock tb = new  TextBlock();
     tb.FontFamily = new  System.Windows.Media.FontFamily( "微软雅黑" );
     tb.FontSize = 50;
     tb.Text = "hello" ;
     System.Diagnostics.Debug.WriteLine( "宽度:"  + tb.ActualWidth + " 高度:"  + tb.ActualHeight);

 这个方法很简单,但是到windows 8上面就不一样了。

在win8 metro程序里面,TextBlock必须要显示到UI上才能得到它的宽度和高度。这就麻烦了。

最后发现一个东西能够将它量出来。那就是矩形。

Rect rect = new  Rect(0, 0, 1024, 1024);
 
TextBlock tb = new  TextBlock();
tb.FontFamily = new  FontFamily( "微软雅黑" );
tb.FontSize = 50;
tb.Text = "hello" ;
tb.Arrange(rect);
System.Diagnostics.Debug.WriteLine( "宽度:"  + tb.ActualWidth + " 高度:"  + tb.ActualHeight);

借鉴2:在stackoverflow上找到了

how to calculate the textbock height and width in on load if i create textblock from code?

4 down vote favorite
TextBlock tbl= new TextBlock(); tbl.text="Kishore"; double x=tbl.ActualHeight; double y=tbl.ActualWidth;

If i execute the code from the loaded event in Metro - winRT will return 0 for both.

How can I get the ActualWidth in the Loaded or SizeChanged event?

share | improve this question
 
 
WPF had methods like arrange/measure, you gave available space and got dimensions as a result. Isn't there something similar in Jupiter? –   Filip Skakun  May 12 '12 at 0:30

1 Answer

active oldest votes
up vote 5 down vote accepted

Call Measure() then Arrange() and then ActualWidth and ActualHeight will be updated.

share | improve this answer
 
 
First, Measure is called, then Arrange. –   HCL  Nov 10 '12 at 11:05
 
Right, of course! –   Filip Skakun  Nov 10 '12 at 16:25


你可能感兴趣的:(metro,windows8,ActualWidth,TextBox宽度)