Search code examples
wpfxaml

Multiline text in button with mouse over trigger in style


I have some wpf buttons which I want to change their background color when I hover or click on them, so I used created this style, that works perfectly.

<Style x:Key="TestStyle" TargetType="{x:Type Button}">
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="FontSize" Value="25"/>
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Background" Value="Blue" />
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="VerticalAlignment" Value="Stretch" />
    <Setter Property="Width" Value="100" />
    <Setter Property="Margin" Value="10,0" />
    <Setter Property="Template">
       <Setter.Value>
           <ControlTemplate TargetType="{x:Type Button}">
               <Border x:Name="Border" Background="{TemplateBinding Background}">
                   <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
               </Border>
               <ControlTemplate.Triggers>
                   <Trigger Property="IsMouseOver" Value="True">
                       <Setter Property="Background" Value="Red" />
                   </Trigger>
                   <Trigger Property="IsPressed"   Value="True">
                       <Setter Property="Background" Value="Green" />
                   </Trigger>
               </ControlTemplate.Triggers>
           </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Then, I wanted to add textwrapping to the button, also in the style, using this code:

<Style x:Key="fie" TargetType="Button"\>
    <Setter Property="Template"\>
        <Setter.Value\>
            <ControlTemplate TargetType="{x:Type Button}"\>
                <TextBlock Text="{TemplateBinding Content}" FontSize="20" TextWrapping="Wrap"/\>
            </ControlTemplate\>
        </Setter.Value\>
    </Setter\>
</Style\>

Any hint how could I merge both without having errors?


Solution

  • Try this:

    <ControlTemplate TargetType="{x:Type Button}">
        <Border x:Name="Border" Background="{TemplateBinding Background}">
            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
                <ContentPresenter.Resources>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="TextWrapping" Value="Wrap" />
                    </Style>
                </ContentPresenter.Resources>
            </ContentPresenter>
        </Border>
        <ControlTemplate.Triggers>
            ...
        </ControlTemplate.Triggers>
    </ControlTemplate>