2011-02-22 26 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