WPF实现动画的方式:
- 基于计时器的动画
建立一个定时器,然后根据其频率循环调用函数或者一个事件处理函数,在这个函数中可以手工更新目标属性,直到达到最终值,这时可以停止计时器。
案例:
效果图:
XAML:
<Window x:Class="WpfDispatcherTimerAnimation.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:WpfDispatcherTimerAnimation" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Ellipse Name="rectangle" Height="20" Width="20" Fill="Aquamarine"/>
<Button Content="开启动画" Click="ButtonBase_OnClick" Height="30" Width="90" Grid.Row="1"/>
</Grid>
</Window>
C#代码:
using System;
using System.Windows;
using System.Windows.Threading;
namespace WpfDispatcherTimerAnimation
{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window {
public MainWindow()
{
InitializeComponent();
}
/// <summary> /// 长方形减小计时器 /// &