locked
ActualWidth in TextBlock RRS feed

  • Question

  • Lets say I have some XAML like this:

     <StackPanel><TextBlock Text="Blah Blah Blah" /></StackPanel>

    In this case, the Width is NaN, as I expect, because it grows with the size of the StackPanel.

    Unfortunately, ActualWidth does not give me the results I expect.  ActualWidth is not bound by the size of the StackPanel.  It is bound to the length of the rendered text, even if that text blows past the size of the parent StackPanel.

     For instance, if StackPanel.ActualWidth is 400, and my text is bigger than 400, my TextBlock.ActualWidth might be 556 (or whatever).  A button in the same situation does not behave this way.

     This is a problem for me because I am trying to implement an attached behavior that implements TrimmingText (elipsis at the end if the text is cropped). It works great if the Width property is explicitly set, but in a more dynamic case, I can't get it to work.

    Any thoughts?

    Brian

    Thursday, June 4, 2009 11:06 AM

Answers

  • String trimming is determined by container size, so It's quite acceptable for me to access textblock's parent to get display width.

    considering textblock's parent not always available, we could design some fallback strategy, for example:

    if user set string trimming length, then use user set value

    else if parent is FrameworkElement, then use ((FrameworkElement)mytextblock.Parent).ActuralWidth

    else do something else.

    Wednesday, June 10, 2009 1:44 AM

All replies

  • How about if you wrap a Border control around the TextBlock, and use the ActualWidth of the Border control to do what you want?
    Thursday, June 4, 2009 1:56 PM
  •  So, that works... I can't add it to my attached behavior, since I don't know the context that the TextBlock is in... but as long as I reauire that the Width property be set, my attached behavior will work when it gets set.  It is up to the user, unfortunately, to determine how to set that width.

    Thursday, June 4, 2009 3:14 PM
  • String trimming is determined by container size, so It's quite acceptable for me to access textblock's parent to get display width.

    considering textblock's parent not always available, we could design some fallback strategy, for example:

    if user set string trimming length, then use user set value

    else if parent is FrameworkElement, then use ((FrameworkElement)mytextblock.Parent).ActuralWidth

    else do something else.

    Wednesday, June 10, 2009 1:44 AM