How to get the actual width of TextBlock?

奇 卢 181 Reputation points
2021-05-19T05:27:59.133+00:00

I defined a TextBlock object in the form and set a string for it. Now I want to get its actual pixel width. When I use the following method, cs0618 warning appears. Is there any other way to get it?

var fromatted = new FormattedText(
                        text.Text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,
                        new Typeface(text.FontFamily, text.FontStyle, text.FontWeight, text.FontStretch),
                        text.FontSize, text.Foreground);
Developer technologies Windows Presentation Foundation
{count} votes

Accepted answer
  1. DaisyTian-1203 11,646 Reputation points
    2021-05-19T07:48:21.013+00:00

    Solution: Please add ,VisualTreeHelper.GetDpi(this).PixelsPerDip after your text.Foreground.

    Explanation: You use the Obsolete FormattedText(String, CultureInfo, FlowDirection, Typeface, Double, Brush), which need to use PixelsPerDip to override , you could refer to official document: FormattedText(String, CultureInfo, FlowDirection, Typeface, Double, Brush) for more details. Its corresponding new method is FormattedText(String, CultureInfo, FlowDirection, Typeface, Double, Brush, Double)

    Updated code:

    var fromatted = new FormattedText(  
                             text.Text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,  
                             new Typeface(text.FontFamily, text.FontStyle, text.FontWeight, text.FontStretch),  
                             text.FontSize, text.Foreground, VisualTreeHelper.GetDpi(this).PixelsPerDip);  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Sam of Simple Samples 5,546 Reputation points
    2021-05-19T05:35:16.59+00:00

    See the following. If these do not help then your question is not clear.


  2. Viorel 122.6K Reputation points
    2021-05-19T19:30:15.997+00:00

    If you need a text block that is resized automatically according to text, then check an example:

    <TextBlock HorizontalAlignment="Left" VerticalAlignment="Top" Margin="50,50,0,0" Text="Some text" />
    

    Put it inside a <Grid>, for example. You do not have to calculate and set the width.

    I think that such textblock can be inserted programmatically too; then you can get its actual width and reposition it. But maybe you should avoid explicit positioning using the corresponding alignment and margin properties.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.