Question

I have a standard Button Style applied accross my application that specifies a mouseover style that changes the text content from white to black. To achieve this I have tried modifying the button template, removing the ContentPresenter and replacing it with a TextBlock. However, this means that I can't have mixed content such as:

<Button
    <Button.Content>
        <StackPanel Orientation="Horizontal">
            <Path Margin="3" Width="12.375" Height="9.70833" Canvas.Left="0" Canvas.Top="0"
                  Stretch="Fill" Fill="#FF115485"
                  Data="F1 M 18.8333,7.08333L 16.7083,4.91667L 10.5,10.5417L 8.52083,8.6875L 6.45833,10.4792L 10.4792,14.625L 18.8333,7.08333 Z "/>
            <TextBlock Margin="3">Hello</TextBlock>
        </StackPanel>
    </Button.Content>
</Button>

To improve the situation, I then put the ContentPresenter back in, and on my (text only) buttons specified a ContentTemplate like this:

<Button IsDefault="True" Content="Text only Button"
        ContentTemplate="{StaticResource TextButtonTemplate}"
        Command="{Binding ...}" 
        CommandParameter="{...}" />

And with a Template defined as below. This template will only work for Buttons with textual content, with other templates defined as needed for mixed content.

<DataTemplate x:Key="TextButtonTemplate">
    <TextBlock Text="{TemplateBinding Content}"
               Foreground="{Binding Path=Foreground,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Button}}" />
</DataTemplate>

Does anyone know if there is a way I can improve this further by keeping the desired mouseover style, without having to define custom templates?

Was it helpful?

Solution

Assuming the content doesn't explicitly set any colors on its own, you can accomplish this like so:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="TextBlock.Foreground" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

This works because TextBlock.Foreground is an inherited property. As long as the controls inside your Button's contents don't explicitly set their own foreground, this will work. If they set their own colors, all bets are off.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top