我正在尝试在 Windows Phone 7 Silverlight 项目中使用 VisualStateManager 在 UserControl 上启动动画,但它不起作用。GoToState 只是继续返回 false。
该代码由一个 VisualState 行为组成,当数据上下文上的状态属性发生更改时运行 GoToState,当单击 UI 中的按钮时会发生这种情况:
我究竟做错了什么?
XAML:
<Grid>
<UserControl x:Name="_testSubject" l:VisualStates.CurrentState="{Binding State}" />
<Button VerticalAlignment="Bottom" Content="Change state" Click="Button_Click" />
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="State2">
<Storyboard>
<ColorAnimation From="Red" To="Green" Duration="0:0:10" Storyboard.TargetProperty="Background" Storyboard.TargetName="_testSubject" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
C#:
public class Test : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); }
string _state;
public string State { get { return _state; } set { _state = value; OnPropertyChanged("State"); } }
}
public static class VisualStates
{
public static readonly DependencyProperty CurrentStateProperty =
DependencyProperty.RegisterAttached("CurrentState", typeof(String), typeof(VisualStates), new PropertyMetadata(TransitionToState));
public static string GetCurrentState(DependencyObject obj)
{
return (string)obj.GetValue(CurrentStateProperty);
}
public static void SetCurrentState(DependencyObject obj, string value)
{
obj.SetValue(CurrentStateProperty, value);
}
private static void TransitionToState(object sender, DependencyPropertyChangedEventArgs args)
{
Control c = sender as Control;
if (c != null)
{
bool b = VisualStateManager.GoToState(c, (string)args.NewValue, false);
}
else
{
throw new ArgumentException("CurrentState is only supported on the Control type");
}
}
public partial class MainPage : PhoneApplicationPage
{
public MainPage() { InitializeComponent(); }
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
_testSubject.DataContext = new Test();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((Test)_testSubject.DataContext).State = "State2";
}
}