所以我的xaml代码看起来像这样 –
<Grid x:Name="LayoutRoot"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates">
我无法使用GoToVisualState行为,因为我需要在运行此动画之前进行一些检查.所以我想我必须在后面的代码中调用类似GoToState或GoToElementState的东西.
但是,WinRT中似乎不存在ExtendedVisualStateManager.我试过用
VisualStateManager.GetCustomVisualStateManager(this.LayoutRoot)
但它总是返回null.
这有什么解决方法吗?
刚想通了.
首先创建一个帮助程序类,就像我们以前在Silverlight或Windows Phone中使用它一样(我从here获取了这段代码并对其进行了一些修改,因此当一个元素没有附加任何可视状态组时,它会自动进行搜索其父级,直到找到任何).
public class ExtendedVisualStateManager : VisualStateManager { protected override bool GoToStateCore(Control control,FrameworkElement stateGroupsRoot,string stateName,VisualStateGroup group,VisualState state,bool useTransitions) { if ((group == null) || (state == null)) { return false; } if (control == null) { control = new ContentControl(); } return base.GoToStateCore(control,stateGroupsRoot,stateName,group,state,useTransitions); } public static bool GoToElementState(FrameworkElement element,bool useTransitions) { var root = FindNearestStatefulFrameworkElement(element); var customVisualStateManager = VisualStateManager.GetCustomVisualStateManager(root) as ExtendedVisualStateManager; return ((customVisualStateManager != null) && customVisualStateManager.GoToStateInternal(root,useTransitions)); } private static FrameworkElement FindNearestStatefulFrameworkElement(FrameworkElement element) { while (element != null && VisualStateManager.GetCustomVisualStateManager(element) == null) { element = element.Parent as FrameworkElement; } return element; } private bool GoToStateInternal(FrameworkElement stateGroupsRoot,bool useTransitions) { VisualStateGroup group; VisualState state; return (TryGetState(stateGroupsRoot,out group,out state) && this.GoToStateCore(null,useTransitions)); } private static bool TryGetState(FrameworkElement element,out VisualStateGroup group,out VisualState state) { group = null; state = null; foreach (VisualStateGroup group2 in VisualStateManager.GetVisualStateGroups(element)) { foreach (VisualState state2 in group2.States) { if (state2.Name == stateName) { group = group2; state = state2; return true; } } } return false; } }
然后你需要手动将xaml更新为这样的东西 –
<VisualStateManager.CustomVisualStateManager> <common:ExtendedVisualStateManager /> </VisualStateManager.CustomVisualStateManager> <VisualStateManager.VisualStateGroups> <VisualStateGroup .../> </VisualStateManager.VisualStateGroups>
我想这个解决方案的优点是你仍然可以在Blend的States选项卡中看到视觉状态,对于Blend爱好者来说这很酷.