WPF button textwrap style

mmr picture mmr · Apr 16, 2009 · Viewed 55.3k times · Source

How do I change the default textwrapping style of a button in WPF?

The obvious solution of:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="TextWrapping" Value="Wrap"></Setter>
</Style>

doesn't work, because Textwrapping isn't a settable property here, apparently.

If I try:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <TextBlock Text="{Binding}" Foreground="White" FontSize="20" FontFamily="Global User Interface" TextWrapping="Wrap"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I just get a worthless response from the compiler:

Error   5   After a 'SetterBaseCollection' is in use (sealed), it cannot be modified.   

Removing the ControlTemplate tag keeps the error.

The following attempt yields a different error:

    <Setter Property="TextBlock">
        <TextBlock Text="{Binding}" Foreground="White" FontSize="20" FontFamily="Global User Interface" TextWrapping="Wrap"/>
    </Setter>

Error   5   The type 'Setter' does not support direct content.  

I see that I can set the textwrapping for each button individually, but that's pretty asinine. How can I do it as a style? What are the magic words?

And for future reference, where can I find a list of these magic words, so I can just do this on my own? The MSDN entry is pretty useless when I try to find out about which properties can be set by the setter.

Answer

Rob picture Rob · Sep 19, 2013

To expand Eric's answer with an example:-

<Button Name="btnName" Width="50" Height="40">
   <TextBlock Text="Some long text" TextWrapping="Wrap" TextAlignment="Center"/>
</Button>