【问题标题】:Applying animations in MVVM? (old method was done dynamically in code-behind)在 MVVM 中应用动画? (旧方法在代码隐藏中动态完成)
【发布时间】:2013-09-01 07:20:33
【问题描述】:

我正在努力采用 MVVM 设计模式,但遇到了一些障碍,其中之一是:

我有一个 Listbox 由绑定的 Monster 对象填充,每个对象都包含一个表示 Monster 生命值的 ProgressBar

然后我在列表框外有一个“攻击”按钮,它会导致选定的怪物在被点击时受到伤害。 (SelectedMonster 是我的 ViewModel 中的一个属性,它被双向绑定到 ListBox 的 SelectedItem 属性。

所有这些都很好用。当点击按钮时,选中的怪物受到伤害,进度条会相应更新。

问题是,我想做的是在 ProgressBar 更改时应用动画。

以前,当我在 ListBox 的每一行中都有一个“攻击”按钮时,我是在代码中动态设置动画并且效果很好(使用我在网上找到的帮助方法 FindDescendent):

Page.xaml

<Storyboard x:Name="MonsterHPStoryboard">
    <DoubleAnimation x:Name="MonsterHPAnimation" Storyboard.TargetProperty="Value" />
</Storyboard>

Page.xaml.cs

private void AttackMonsterButton_Click(object sender, RoutedEventArgs e)
{
    Monster Monster = (sender as FrameworkElement).DataContext as Monster;

    ProgressBar HPBar = FindDescendant<ProgressBar>(((sender as Button).Parent as Grid).Parent as Grid);

    Storyboard.SetTarget(MonsterHPAnimation, HPBar);

    // set the From value to the Monster's current HP
    MonsterHPAnimation.SetValue(DoubleAnimation.FromProperty, (Double)Monster.HP);

    // set the To value to the Monster's HP after being attacked - returned by ThePlayer.Attack()
    MonsterHPAnimation.SetValue(DoubleAnimation.ToProperty, (Double)ThePlayer.Attack(Monster, Battle));

    // set the duration of the animation to 250 ms
    MonsterHPAnimation.SetValue(DoubleAnimation.DurationProperty, new Duration(TimeSpan.FromMilliseconds(250)));

    MonsterHPStoryboard.Begin();
}

关于如何通过 MVVM 路线完成此任务的任何想法?有没有更简单的方法来告诉动画在 ProgressBar 的值发生变化时播放?

提前致谢!

【问题讨论】:

    标签: silverlight windows-phone-7 data-binding mvvm windows-phone


    【解决方案1】:

    使用带有动画动作的交互触发器。您应该能够在声明性 XAML 中完成所有操作。触发器将是实现 INPC 的 VM 中的一个属性。然后您将使用工作线程并使用进度事件来更新绑定到交互触发器的属性。

    【讨论】:

    • 谢谢!你的意思是事件触发?另外我在 Blend 中没有看到“动画动作”...我想知道是不是因为我正在运行 VS2010 版本(显然“表达式”行已停产)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多