Have a look at the XAML below.
I want the «HelloText» TextBlock to “glow” when I hover over it with the mouse (thus the storyboard instead of a trigger on IsMouseOver). The code below doesn’t work since two TextBlocks have the same name. How can I edit this code so that I can apply «MyStackPanelStyle» to more than one StackPanel?
<Window.Resources>
<Style TargetType="StackPanel" x:Key="MyStackPanelStyle">
<Style.Triggers>
<EventTrigger RoutedEvent="StackPanel.MouseEnter">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Duration="0:0:0.5" Storeboard.TargetName="HelloText" Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)" To="LightGray" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="StackPanel.MouseLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Duration="0:0:0.5" Storeboard.TargetName="HelloText" Storyboard.Target="TextBlock" Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)" To="#505050" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel style="MyStackPanelStyle">
<TextBlock Name="HelloText" Text="Hello" />
<TextBlock Text="World" />
</StackPanel>
<StackPanel style="MyStackPanelStyle">
<TextBlock Name="HelloText" Text="Hello" />
<TextBlock Text="World" />
</StackPanel>
Edit:
I’ve read an article by Sergio Loscialo which lookded promising. Unfortunately, this solution applies to all target elements that inherit from AnimationPlaceholder, which means that it won’t work when I’ve more than one of these StackPanels on my page.
Sounds likes you want to be providing a
Stylefor theTextBlockand not theStackPanel:Please note the same effect can be achieved with
IsMouseOverby setting theEnterActionsandExitActions:The above answer assumes you don’t have a requirement which relates the
TextBlockto yourStackPanel(e.g. always animate the firstTextBlockin theStackPanel, or always animate aTextBlockwith a certain name). If this was the case, relying on theNamewould be brittle and you would be better off creating a custom control or user control with a property or named part for the special content.Edit:
To start the animations when the mouse enters the
StackPanelyou could just adapt the above solution to use aDataTriggerinstead:Hope this helps!