状态迁移(State Transitions)
状态迁移是指控件从一个状态过渡到另外一个状态,如Button控件从MouseOver状态到Pressed状态这个过渡过程,通过Storyboard来定义的动画。
状态迁移在Silverlight 2中使用VisualTransition类来表示,它的定义如下代码所示:
public class VisualTransition
{
public VisualTransition();
public Duration Duration { get; set; }
public string From { get; set; }
public Storyboard Storyboard { get; set; }
public string To { get; set; }
}
状态组(StateGroups)
状态组,是把控件所有互斥的状态放在同一个组中,这样一个状态它只能位于一个组中,所谓的互斥是指控件不肯能同时具有该组中的两种状态,如Checked和Unchecked两个状态不可能同时存在。以CheckBox控件为例,我们来看一下它的状态组:
从上表中我们可以看到,对于CheckBox控件来说,它有三个状态组:FocusStates、CommonStates、CheckStates。一个CheckBox控件可以同时为Focused、MouseOver和Indeterminate状态,因为它们处在不同的状态组。现在对于这个问题:
“CheckBox控件的状态是什么?”答案应该由三部分组成,分别为三个状态组中的一个。状态组是在Silverlight 2中提出的一个新的概念,它由VisualStateGroup类来提供,其中除了状态组名属性外,维护了一个视觉状态的集合和一个状态迁移的集合,如下代码所示:
public sealed class VisualStateGroup : DependencyObject使用状态组是一个非常棒的模型,在Beta 1中,CheckBox控件有12种状态(其中Focus在Beta 1中是作为部件而不是状态),这12种状态是通过CommonStates和CheckStates组合而成的,如PressedUnchecked、MouseOverChecked等,而在Beta 2中,加上FocusStates状态,CheckBox控件总共只有10种状态。
{
public VisualStateGroup();
public string Name { get; }
public Collection<VisualState> States { get; set; }
public Collection<VisualTransition> Transitions { get; set; }
}
控件的状态和状态组是通过TemplateVisualState特性来声明的,如在CheckBox控件中的声明如下代码所示:
[TemplateVisualStateAttribute(Name = "ContentFocused", GroupName = "FocusStates")]
[TemplateVisualStateAttribute(Name = "MouseOver", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Focused", GroupName = "FocusStates")]
[TemplateVisualStateAttribute(Name = "Checked", GroupName = "CheckStates")]
[TemplateVisualStateAttribute(Name = "Unchecked", GroupName = "CheckStates")]
[TemplateVisualStateAttribute(Name = "Indeterminate", GroupName = "CheckStates")]
[TemplateVisualStateAttribute(Name = "Pressed", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Disabled", GroupName = "CommonStates")]
[TemplateVisualStateAttribute(Name = "Unfocused", GroupName = "FocusStates")]
[TemplateVisualStateAttribute(Name = "Normal", GroupName = "CommonStates")]
public class CheckBox : ToggleButton
{
// ......
}