1. 前言
VisualTransition是控件模板中的重要组成部分,无论是自定义控件或者修改控件样式都会接触到VisualTransition。明明这么重要,博客园上好像都没多少关于VisualTransition的主题。
2. 什么是VisualTransition
VisualTransition动画定义VisualState之前切换时的过渡行为,包括过渡时间和过渡动画。
VisualTransition的类定义如下:
[ContentProperty(Name = "Storyboard")]
public class VisualTransition : DependencyObject, IVisualTransition
{
public VisualTransition();
// 摘要:
// 获取或设置要转换为的 Windows.UI.Xaml.VisualState 的名称。
public string To { get; set; }
//
// 摘要:
// 获取或设置在发生转换时运行的 Windows.UI.Xaml.Media.Animation.Storyboard。
public Storyboard Storyboard { get; set; }
//
// 摘要:
// 获取或设置应用于生成的动画的缓动函数。
public EasingFunctionBase GeneratedEasingFunction { get; set; }
//
// 摘要:
// 获取或设置从一种状态转换到另一种状态所花的时间,以及任何隐式过渡动画应作为过渡行为的一部分运行的时间
public Duration GeneratedDuration { get; set; }
//
// 摘要:
// 获取或设置要转换的 Windows.UI.Xaml.VisualState 的名称。
public string From { get; set; }
}
3.为什么使用VisualTransition
虽然自WPF4以来VisualTransition一直都存在,但很多人还是习惯这样写VisualState:
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="PointerOver">
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="PointOverElement"
Duration="0"
To="1" />
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="PressElement"
Duration="0"
To="1" />
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled" />
</VisualStateGroup>
正确的做法应该是这样:
<VisualStateGroup x:Name="CommonStates">
<VisualStateGroup.Transitions>
<VisualTransition To="PointerOver">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
Storyboard.TargetName="PointOverElement">
<EasingDoubleKeyFrame KeyTime="0"
Value="0" />
<EasingDoubleKeyFrame KeyTime="0:0:2"
Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CubicEase EasingMode="EaseOut" />
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualTransition>
<VisualTransition To="Pressed">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
Storyboard.TargetName="PressElement">
<EasingDoubleKeyFrame KeyTime="0"
Value="0" />
<EasingDoubleKeyFrame KeyTime="0:0:2"
Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<CubicEase EasingMode="EaseOut" />
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualTransition>
<VisualTransition To="Disabled">
<Storyboard Completed="Storyboard_Completed"></Storyboard>
</VisualTransition>
</VisualStateGroup.Transitions>
<