none
Measuring the width of a wpf label

    Question

  • Dear sirs,

    I am creating a charting tool in WPF.  I dynamicaly add the x labels as strings, however I need to know the string width, so I can properly center in underneath the xTick.   Alas, I cant get the width using the myLabel.Width; it returns NaN.  Are there any suggestions?

    Is there a WPF way instead of estimating with system.Drawing?

    Thanks,
    Paulo C
    Friday, January 04, 2008 2:36 AM

Answers

  • If actualWidth and actualHight are NaN, you may have to force a layout using:

     

    myLabel.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

    myLabel.Arrange(new Rect(myLabel.DesiredSize));

     

    Tom

     

    Friday, January 04, 2008 9:34 PM

All replies

  • Height and Width are only defined if you specify them.  If not, they are "NotANumber" as you're seeing.

     

    What you want is the ActualWidth/ActualHeight properties.  These values are set by the layout system and represent a very good estimate of the actual laid-out-width of the control.  Further, they help you deal with centering beneath a control that may be partially clipped.

     

    HTH,

    Matt

    Friday, January 04, 2008 9:20 PM
    Moderator
  • If actualWidth and actualHight are NaN, you may have to force a layout using:

     

    myLabel.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

    myLabel.Arrange(new Rect(myLabel.DesiredSize));

     

    Tom

     

    Friday, January 04, 2008 9:34 PM
  • Tom,

    Thanks for the great assistance.  The labels are now nicely placed!  This was my final code.

    All the best,
    Paulo C.

    //Measure it
    myLabel.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
    Rect measureRect = new Rect(myLabel.DesiredSize);
    myLabel.Arrange(measureRect);

    //Place it in Canvas
    Canvas.SetLeft(myLabel, (pc.x - (measureRect.Width)/2));  
    Saturday, January 05, 2008 12:03 PM