Silverlight: Button template with texttrimming cut off

Posted by dex3703 on Stack Overflow See other posts from Stack Overflow or by dex3703
Published on 2010-12-23T00:20:25Z Indexed on 2010/12/23 16:54 UTC
Read the original article Hit count: 202

I'm replacing the default Button template's ContentPresenter with a TextBlock, so the text can be trimmed when it's too long.

Works fine in WPF. In Silverlight the text gets pushed to one edge and cut off on the left, even when there's space on the right:

alt text

Template is nothing special, just replaced the ContentPresenter with the TextBlock:

            <Border x:Name="bdrBackground" 
            BorderBrush="{TemplateBinding BorderBrush}" 
            BorderThickness="{TemplateBinding BorderThickness}" 
            Background="{TemplateBinding Background}" />

        <Rectangle x:Name="rectMouseOverVisualElement"
            Opacity="0">
            <Rectangle.Fill>
                <SolidColorBrush x:Name="rectMouseOverColor" 
                    Color="{StaticResource MouseOverItemBgColor}"/>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle x:Name="rectPressedVisualElement" 
            Opacity="0" 
            Style="{TemplateBinding Tag}"/>

        <TextBlock x:Name="textblock" 
            Text="{TemplateBinding Content}" 
            TextTrimming="WordEllipsis"
            TextWrapping="NoWrap"
            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
            Margin="{TemplateBinding Padding}" 
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>


        <Rectangle x:Name="rectDisabledVisualElement" 
            Opacity="0" 
            Style="{StaticResource RectangleDisabledStyle}"/>

        <Rectangle x:Name="rectFocusVisualElement" 
            Opacity="0" 
            Style="{StaticResource RectangleFocusStyle}"/>              

    </Grid>
</ControlTemplate>  

How do I fix this?


More info: With the latest comment about HorizontalAlignment, it's clear that SL's implementation of TextTrimming differs from WPF's. In SL, TextTrimming only really works if the text is aligned left. SL isn't smart enough to align the text the way WPF does. For instance:

WPF button:

alt text

SL button with the textblock horizontalalignment = left:

alt text

SL button with textblock horizontalalignment = center:

alt text

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about templates