Sliverlight情景下使用
方法一、 使用VisualStateManager 技术,调用 GoToState()
XAML代码:
<Grid x:Name="LayoutRoot" Background="White">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="myButtonStates">
<VisualState x:Name="Normal"></VisualState>
<VisualState x:Name="Changed">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="myButton" Storyboard.TargetProperty="Width" To="400" Duration="00:00:01">
</DoubleAnimation>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Button Width="100" Height="30" Content="点击我,让我长大" Click="Button_Click" x:Name="myButton"/>
</Grid>
C#代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Windows.VisualStateManager.GoToState(this, "Changed", true);
}
方法二、将Storyboard放在页面 Resources
XAML代码:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<Storyboard x:Name="myButtonChanged">
<DoubleAnimation Storyboard.TargetName="myButton" Storyboard.TargetProperty="Width" To="400" Duration="00:00:01">
</DoubleAnimation>
</Storyboard>
</Grid.Resources>
<Button Width="100" Height="30" Content="点击我,让我长大" Click="Button_Click" x:Name="myButton"/>
</Grid>
C#代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
Storyboard sb = LayoutRoot.Resources["myButtonChanged"] as Storyboard;
sb.Begin();
}
WPF情景下使用
方法一,事件触发器
<Grid>
<Button Width="100" Height="30" Content="点击我,让我长大" x:Name="myButton">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard >
<DoubleAnimation To="400" Storyboard.TargetName="myButton" Storyboard.TargetProperty="Width" Duration="00:00:05">
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</Grid>
方法二,样式触发器
<Grid>
<Grid.Resources>
<Style x:Key="ButtonStyle">
<Style.Triggers>
<Trigger Property="Button.IsPressed" Value="True">
<!--Trigger.EnterActions当设置的属性改变到指定的值时,执行(此示例是IsPressed的值为True时)-->
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="400" Duration="00:00:02" Storyboard.TargetProperty="Width"></DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<!--Trigger.ExitActions当设置的属性还原时执行(此示例IsPressed的值回到False时)-->
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="100" Duration="00:00:02" Storyboard.TargetProperty="Width"></DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<Button Width="100" Height="30" Content="按住鼠标,按钮宽度长大,松开,还原" x:Name="myButton" Style="{StaticResource ButtonStyle}">
</Button>
</Grid>