2011-02-22 24 views
1

我希望我想要做的是能够使用可视状态面板...WPF使用VisualStateManager动画在进出

我想要做的就是有一个按钮,切换两者之间的一个StackPanel陈述:'进'和'出'。然后,我将调用VisualStateManager.GoToState按钮的单击事件,以在两种状态之间切换。

Panel States

我碰到的是我无法弄清楚如何将状态连接到StackPanel中的问题。它不会让我使用Expression Blend。所以我被卡住了......是否有使用VisualStateManager为此面板设置动画的动画? (我知道我可以使用故事板和创建和进出动画,但我假设使用状态,如果可能的话)

我真的希望这是可能的。否则VisualStateManager除了对按钮做噱头翻转效果外,还有什么好处?

感谢您的帮助!

+0

我也尝试将VisualStateGroup添加到窗口的LayoutRoot中,然后在Click事件中将'this'传入VSM中(例如:VisualStateManager.GoToState(this,“In”,true)...但是这对我也不适用。 – 2011-02-24 21:25:32

+0

奇怪...我只是把相同的代码放入WinPhone7项目中,并且它工作正常。 。为什么它可以用于WinPhone7 Silverlight,但不是WPF? – 2011-02-24 21:27:17

回答

2

刚刚解雇了Blend和得到这个:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
    x:Class="WpfApplication1.MainWindow" 
    x:Name="Window" 
    Title="MainWindow" 
    Width="640" Height="480"> 

    <StackPanel x:Name="LayoutRoot"> 
     <VisualStateManager.VisualStateGroups> 
      <VisualStateGroup x:Name="PanelState"> 
       <VisualState x:Name="In"/> 
       <VisualState x:Name="Out"> 
        <Storyboard> 
         <ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="stackPanel"> 
          <EasingThicknessKeyFrame KeyTime="0" Value="-65,15,0,0"/> 
         </ThicknessAnimationUsingKeyFrames> 
        </Storyboard> 
       </VisualState> 
      </VisualStateGroup> 
     </VisualStateManager.VisualStateGroups> 
     <i:Interaction.Behaviors> 
      <ei:DataStateBehavior Binding="{Binding IsChecked, ElementName=toggleButton}" Value="True" TrueState="In" FalseState="Out"/> 
     </i:Interaction.Behaviors> 
     <Button Content="Button" Width="50" HorizontalAlignment="Left" Click="Button_Click"/> 
     <StackPanel x:Name="stackPanel" Height="100" HorizontalAlignment="Left" Margin="0,15,0,0"> 
      <TextBlock><Run Text="Funnytext"/></TextBlock> 
     </StackPanel> 
     <ToggleButton x:Name="toggleButton" Content="Toggle" Width="50" HorizontalAlignment="Left"/> 
    </StackPanel> 
</Window> 

和后面的代码:

private void Button_Click(object sender, System.Windows.RoutedEventArgs e) 
{ 
    var sgs=VisualStateManager.GetVisualStateGroups(LayoutRoot); 
    var sg=sgs[0] as VisualStateGroup; 
    VisualStateManager.GoToElementState(LayoutRoot, ((VisualState) sg.States[sg.CurrentState == sg.States[0]?1:0]).Name,true); 
} 

(不知道是什么的StackPanel你的意思,所以我只包括两名)

编辑:我的坏,没有注意到我没有包括点击处理程序。为了您的方便,我包含了一个使用Togglebutton切换状态的示例...

+0

你甚至没有添加一个事件处理程序到按钮中......你想告诉我什么?我的问题是,使用这个代码,你会如何将状态从out改为in?你在代码隐藏中将什么参数传递给VSM? – 2011-02-24 20:10:38

+0

@ Matt.M:请参阅我编辑过的帖子 – 2011-02-25 22:28:15

+0

非常感谢!所以看起来WPF最容易使用GoToElementState,而不是GoToState,因为视觉状态应用于LayoutRoot。 (对于延迟抱歉,周末无法完成) – 2011-02-28 17:17:47