刚刚想通了。
首先创建一个帮助类,就像我们过去在 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, string stateName, bool useTransitions)
{
var root = FindNearestStatefulFrameworkElement(element);
var customVisualStateManager = VisualStateManager.GetCustomVisualStateManager(root) as ExtendedVisualStateManager;
return ((customVisualStateManager != null) && customVisualStateManager.GoToStateInternal(root, stateName, 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, string stateName, bool useTransitions)
{
VisualStateGroup group;
VisualState state;
return (TryGetState(stateGroupsRoot, stateName, out group, out state) && this.GoToStateCore(null, stateGroupsRoot, stateName, group, state, useTransitions));
}
private static bool TryGetState(FrameworkElement element, string stateName, 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 爱好者来说,这真是太酷了。