wpf的VisualStateManager

wpf4正式测试成功完成了VisualStateManager的功能。在此之前我没有确认wpf3.5是否已经支持此功能。以下是我使用vs2010 rc写的demo程式:

1.xaml部份一般都是用blend来设计的state。这里为了文章篇写的方便,我直接把xaml放出来.在blend中只能用鼠标拖拖放放即可弄出很多state。这功能对很多应用都很有好处。不用每次都自己写动画。还支持动画延时效果。

xaml部分:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" xmlns:ee="http://schemas.microsoft.com/expression/2010/effects" x:Class="WpfApplication1.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="LayoutRoot">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="VisualStateGroup">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.3"/>
</VisualStateGroup.Transitions>
<VisualState x:Name="nothing">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="button1">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="change">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)" Storyboard.TargetName="button1">
<EasingDoubleKeyFrame KeyTime="0" Value="50.596"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="216.2,176.8,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.5,0.5">
<Button.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Button.RenderTransform>
</Button>

</Grid>
</Window>

代码部份:

a)使用State:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
button1.MouseEnter += button1_MouseEnter;
button1.MouseLeave += button1_MouseLeave;
}

void button1_MouseLeave(object sender, MouseEventArgs e)
{
VisualStateManager.GoToElementState(this.LayoutRoot, "nothing", true);
}

void button1_MouseEnter(object sender, MouseEventArgs e)
{
VisualStateManager.GoToElementState(this.LayoutRoot, "change", true);
}
}
}

至此,一个简单的state即完成。当鼠标移动到button时,button要翻转,鼠标离开时button会回到原样.

posted @ 2012-12-10 09:25  黎东海  阅读(2667)  评论(0编辑  收藏  举报