Patrick
Patrick

Reputation: 167

Change button content foreground or stroke color using a custom button style

I try to change the Stroke of an Ellipse that is the Content of a Button on mouse hover using a custom button style like this:

<Style x:Key="MyButtonStyle" TargetType="ButtonBase">
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ButtonBase">
                <Grid x:Name="RootGrid">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="PointerOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="Blue" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter
                            x:Name="ContentPresenter"
                            Foreground="{TemplateBinding Foreground}" 
                            ContentTemplate="{TemplateBinding ContentTemplate}"
                            ContentTransitions="{TemplateBinding ContentTransitions}"
                            Content="{TemplateBinding Content}" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Why does only the TextBlock with the Text "Working" change its Foreground property?

<Button x:Name="MyButton" Style="{StaticResource MyButtonStyle}">
    <StackPanel>
                <Ellipse Width="20" Height="20" Stroke="{x:Bind MyButton.Foreground, Mode=OneWay}"></Ellipse>
                <TextBlock Foreground="{x:Bind MyButton.Foreground, Mode=OneWay}" Text="Not Working" />
                <TextBlock Text="Working" />
    </StackPanel>
</Button>

Upvotes: 0

Views: 1136

Answers (1)

Justin Lam
Justin Lam

Reputation: 799

  1. Your visual state animation is modifying the ContentPresenter's foreground not the Button (MyButton)'s foreground.
  2. Use a ContentControl instead of a ContentPresenter in order to access other properties within the template.
  3. Access some other control's Foreground such as the following.

Code:

<StackPanel>
     <Ellipse Width="20" Height="20" Stroke="{x:Bind MyText.Foreground, Mode=OneWay}"></Ellipse>
     <TextBlock Foreground="{x:Bind MyText.Foreground, Mode=OneWay}" Text="Not Working" />
     <TextBlock x:Name="MyText" Text="Working" />
</StackPanel>

Upvotes: 1

Related Questions