2011-03-06 16 views
4

是否可以在代碼中以編程方式將VisualState添加到自定義控件模板VisualStateManager中?
例如,我可以在設計時手動添加到CustomControl模板此XAML:如何在代碼中動態地將新的可視狀態添加到自定義控件模板?

<VisualState x:Name="First"> 
    <Storyboard> 
     <ColorAnimation Duration="0:0:0" 
         Storyboard.TargetName="SBorder" 
         Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)" To="Red" /> 
    </Storyboard> 
</VisualState> 

但我怎麼能添加在運行一個新VisualState

回答

1

我認爲這是可行的,但絕不是簡單的...

這應該工作:

Grid grid = this.Template.FindName("RootElement", this) as Grid; 
(VisualStateManager.GetVisualStateGroups(grid)).Add(new VisualStateGroup() { /* the code for your visualstategroup here */ }); 

(你需要根據你的模板的根元素的名稱的類型,以適應,以及你設置視覺狀態管理者的地方,但總的來說這可以工作。

此外,這增加了一個新的visualStateGroup,不只是一個visualState。如果你想添加一個VisualState到現有的VisualStateGroup,你必須先從集合中獲得該組,東西

基本上但這是常見的「從集合獲取元素」:

  1. 獲取包含visualStateManager
  2. 使用VisualStateManager.GetVisualStateGroups()靜態方法來得到當前visualStateGroups模板的元素
  3. 拿到小組第一你想從集合或創建一個新的並將其添加到集合
  4. 在此組中添加一個新的visualState

希望這有助於。

1

你應該使用XAML我建議創建集團本身,那麼 你必須找到你正在尋找這樣的VisualStateGroup:

VisualStateGroup visualStateGroupLookingFor = null; 
var visualStateGroups = (VisualStateManager.GetVisualStateGroups(LayoutRoot)); 
foreach (VisualStateGroup state in visualStateGroups) { 
    if (state.Name == "VisualStateGroupMine") { 
     visualStateGroupLookingFor = state; 
     break; 
     } 
    } 

然後,你必須創建一個新的VisualState和故事板添加,例如:

var visualState = new VisualState(); 
var storyBoard = new Storyboard(); 

現在,創建動畫:

var animation = new DoubleAnimation(); 
animation.To = 10.0; 

並設置動畫的目標:

//assuming this is instance of class ClassFoo 
//and you want to animate it's Width 
Storyboard.SetTarget(animation, this); 
Storyboard.SetTargetProperty(animation, new PropertyPath(ClassFoo.WidthProperty)); 

最後動畫(S)添加到您的故事板,給它一個名稱,將其添加到visualstategroup:

storyBoard.Children.Add(animation); 
visualState.Storyboard = storyBoard; 
visualState.Name = "CoolNameLikeWidthAnimation"; 
visualStateGroupLookingFor.States.Add(visualState); 

完蛋了,觸發它像往常一樣用

VisualStateManager.GoToState(this, "CoolNameLikeWidthAnimation", true); 
相關問題