一、使矩形边框产生动画需要使用ColorAnimation,并且要注意,要给需要添加动画的属性(这里是Stroke.Color)设置初始值,不然会触发异常。
MainWindow.xaml文件代码(按键盘→键可以看到右侧被挡住的代码)
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ResourceDictionary>
<Style TargetType="Rectangle">
<Setter Property="Stroke" Value="Black"/>
<Setter Property="Fill" Value="AliceBlue"/>
<Setter Property="StrokeThickness" Value="2"/>
<Style.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="LawnGreen" Duration="0:0:0.5" Storyboard.TargetProperty="Stroke.Color"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Duration="0:0:1" Storyboard.TargetProperty="Stroke.Color"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Rectangle Grid.Column="1" Grid.Row="1"/>
<Rectangle Grid.Column="1" Grid.Row="2"/>
<Rectangle Grid.Column="2" Grid.Row="1"/>
<Rectangle Grid.Column="2" Grid.Row="2"/>
<Rectangle Grid.Column="3" Grid.Row="1"/>
<Rectangle Grid.Column="3" Grid.Row="2"/>
</Grid>
</Window>
代码效果如下: