views:

572

answers:

1

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

+1  A: 

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.

Noldorin
Yeah, that is about the best I can do. My behavior requires that the Width property be set. If the user of the behavior puts the TextBlock in a container that changes that width, they will have to hack it to update the Width property when the container size changes to the container's ActualWidth. Kinda ungly, but it works.
Brian Genisio
@Brian: Yeah, I agree it's somewhat ugly, but it in fact used to be the *only* solution for many layout tasks in WinForms. Regarding your case, you could make it slightly easier for the user in that the container control could iterate over all its child TextBlocks and set the width automatically.
Noldorin