2010-01-28 55 views
2

是否有嵌套的視覺狀態。我的意思是如果一個ParentControl有一個ChildControl並且都有它們自己的可視狀態,是否可以通過設置ParentControl的狀態來相應地改變ChildControl的狀態。Silverlight VisualStateManager

回答

1

您需要調用GoToState方法來更改子控件的視覺狀態。

既然你需要調用一個方法,你不能在父控件的可視化狀態管理器中使用Storyboard,因爲這些只能動畫屬性。

因此,您需要在子控件中編寫一些代碼。監視父母的狀態並做出適當的迴應。

有許多不同的方法可以做到這一點,但信息的關鍵金塊是使用VisualStateManager.GetVisualStateGroups方法來找到你感興趣的父VisualStateGroup,然後附加到該組的CurrentStateChanging事件。因此,當它感興趣的狀態正由父代轉換到其可以通過GoToState對其本身進行適當調用時,可以通知子控件中的代碼。

+0

我希望有更多的陳述方法。這在某種程度上迫使我每次使用它時都會對控制進行更改。我想我只需要實現一個依賴屬性,它可以滿足我需要,然後在父母狀態中使用它。 – 2010-01-28 17:11:11

+0

@Petar:好的,如果你需要一個更一般的解決方案來將控件粘合在一起,那麼在一個附屬屬性中定義的一些外部對象將會分離控件。然而,你這樣做,它還不存在,你需要編寫一些代碼來實現它。 – AnthonyWJones 2010-01-28 17:22:29

0

我只是要聲明一個新的依賴項屬性:

public static readonly DependencyProperty StateProperty = 
     DependencyProperty.Register("State", 
     typeof(string),       
     typeof(TextBlockControl), 
     new PropertyMetadata("Top", 
     new PropertyChangedCallback(StateChanged))); 

    [Category("DigItOut"), Description("State")] 
    public string State 
    { 
     get 
     { 
      return this.GetValue(StateProperty).ToString(); 
     } 
     set 
     { 
      this.SetValue(StateProperty, value); 
     } 
    } 

    private static void StateChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)  
    { 
     if (!String.IsNullOrEmpty(args.NewValue.ToString())) 
      VisualStateManager.GoToState(sender as TextBlockControl, args.NewValue.ToString(), true); 
    } 

然後設置它從它的父母狀態:

<VisualStateManager.VisualStateGroups> 
     <VisualStateGroup x:Name="States"> 
      <VisualState x:Name="Reverse"> 
       <Storyboard> 
        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="textBlockControl" Storyboard.TargetProperty="(TextBlockControl.State)"> 
         <DiscreteObjectKeyFrame KeyTime="00:00:00"> 
          <DiscreteObjectKeyFrame.Value> 
           <System:String>Bottom</System:String> 
          </DiscreteObjectKeyFrame.Value> 
         </DiscreteObjectKeyFrame> 
        </ObjectAnimationUsingKeyFrames> 
       </Storyboard> 
      </VisualState> 
      <VisualState x:Name="Straight"/> 
     </VisualStateGroup> 
    </VisualStateManager.VisualStateGroups> 

但是,如果我仍然希望對使用的控制過渡,那麼我將不得不尋找另一種解決方案。可能是第二個屬性。