上一篇中的效果是,鼠标进入 StackPanel 会触发它倾斜一个角度,我有一个想法:鼠标进入 StackPanel 的同事如何更改它内部位 TextBlock 文字的颜色,鼠标离开后又恢复颜色。
方法是在 DataTemplate 中对 StackPanel 增加 EventTrigger 实现的。
▲ 实现效果,鼠标离开后归正的同事文字颜色恢复白色。
DataTemplate - FruitInfoDT.xaml :
<UserControl x:Class="MyUILib.FruitInfoDT"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type StackPanel}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="5"></RotateTransform>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="#3B9CFB" />
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<StackPanel Orientation="Vertical" Margin="10" x:Name="sp">
<StackPanel.Triggers>
<EventTrigger RoutedEvent="StackPanel.MouseEnter" SourceName="sp">
<BeginStoryboard>
<Storyboard >
<ColorAnimation Storyboard.TargetName="txb" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"
From="White" To="Red" Duration="00:00:0.2"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="StackPanel.MouseLeave" SourceName="sp">
<BeginStoryboard>
<Storyboard >
<ColorAnimation Storyboard.TargetName="txb" Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"
From="Red" To="White" Duration="00:00:0.3"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</StackPanel.Triggers>
<Image Source="{Binding Img}" Width="96" Height="96" />
<TextBlock HorizontalAlignment="Center" Foreground="White" Text="{Binding Info}" Name="txb"/>
</StackPanel>
</Grid>
</UserControl>
参考:
WPF中如何利用Style样式的EventTrigger和ColorAnimation为控件实现鼠标滑过或按下时改变背景颜色
wpf 通过EventTrigger用一个控件控制另一个控件