R – Problem with TextBlock.ActualWidth in Silverlight 2.0

silverlight-2.0textblock

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 and is not explicitly set.

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

Best Answer

I don't believe this is such a simple issue as it might appear (or at least did to me). In WPF, I would typically recommend to use a DockPanel control instead of StackPanel. For Silverlight, the problem is worsened by the fact that there doesn't exist a DockPanel control. My one suggestion (that may or may not work) would be to update the Width property of the TextBlock to the ActualWidth property of the parent StackPanel whenever the parent change size. Not the most elegant solution, but it may unfortunately be required.

Related Topic