我需要知道Textblock在渲染之前的大小。 我已经完成了这个link,但它不起作用(可能是我做错了什么)。 我的Textblock绑定到ViewModel中的属性,在后面的代码中我正在监视文本更改事件。
XAML:
<TextBlock Text="{Binding Path=MyProperty, NotifyOnTargetUpdated=True}"
TargetUpdated="OnTargetUpdated"/>
和代码背后:
private void OnTargetUpdated(object sender, DataTransferEventArgs e)
{
var tb = sender as TextBlock;
var text = tb .Text; // here I can see updated Text
var size = tb.DesiredSize; // here DesireSize value is 0
tb.Measure(new Size(Double.PositiveInfinity,
Double.PositiveInfinity));
tb.Arrange(new Rect(tb.DesiredSize));
var width = tb.ActualWidth; // here actual width is coming 0
}
答案 0 :(得分:1)
我有同样的问题。我调用UpdateLayout()方法更新了ActualHeight和ActualWidth
var viewbox = new Viewbox { Child = contentPresenter };
viewbox.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
viewbox.Arrange(new Rect(viewbox.DesiredSize));
viewbox.UpdateLayout();
viewbox.Child = null;
答案 1 :(得分:0)
试试这个:how to calculate the textbock height and width in on load if i create textblock from code?
调用Measure()然后调整(),然后更新ActualWidth和ActualHeight。