Using Silverlight 4 & WPF 4, I'm trying to create a button style that alters the text color of any contained text when the button is mouseover'd. Since I'm trying to make this compatible with both Silverlight & WPF, I'm using the visual state manager:
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="outerBorder" CornerRadius="4" BorderThickness="1" BorderBrush="#FF757679">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Duration="0" To="#FFFEFEFE"
Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)"
Storyboard.TargetName="contentPresenter"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid>
<Border x:Name="Background" CornerRadius="3" BorderThickness="1" BorderBrush="Transparent">
<Grid>
<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}"/>
</Grid>
</Border>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
Since this is a template for a regular old button, I know there's no guarantee that there even is a textblock inside of it, and at first I wasn't sure this was even possible. Curiously, the text color does change if the button is declared like:
<Button Content="Hello, World!" />
but it does not change if the button is declared like:
<Button>
<TextBlock Text="Hello, World!" /> <!-- Same result with <TextBlock>Hello, World </TextBlock> -->
</Button>
Even though the visual tree (when inspected in snoop) is identical (Button -> ContentPresenter -> TextBlock), with the caveat that the textblock created in the 1st version has it's data context set to "Hello, World", whereas the textblock in the second version merely has its text property set. I'm presuming this has something to do with the order of control creation (the first version the button creates the TextBlock, in the second version the textblock might be created first? Really not sure on this).
In the course of researching this, I've seen some solutions that work in Silverlight (like replacing the ContentPresenter with a ContentControl), but that won't work in WPF (program actually crashes).
Since this is in the button's control template, and I'd like to use the VSM if possible, I think that also rules out explicitly changing the Button's own Foreground property (I don't know how I would access that from within the template?)
I'd really appreciate any help, advice anyone could give.