0

I need to know the size of my Textblock before it is rendered. I have gone through this link but its not working (may be I am doing something wrong). My Textblock is binded to the property in a ViewModel and in code behind I am monitoring the text changed event.

XAML:

<TextBlock Text="{Binding Path=MyProperty, NotifyOnTargetUpdated=True}" 
           TargetUpdated="OnTargetUpdated"/>

and code behind:

 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
    } 
Community
  • 1
  • 1
Mohd Ahmed
  • 1,422
  • 13
  • 27

2 Answers2

1

I had same problem. I called UpdateLayout() method which updated ActualHeight and 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;
deathrace
  • 908
  • 4
  • 22
  • 48
0

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

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

Community
  • 1
  • 1
user1666620
  • 4,800
  • 18
  • 27