正如 HighCore 评论的那样,使用EventToCommand
. 它使用起来非常简单,尽管您首先需要 Blend SDK。
...
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL4"
xmlns:im="clr-namespace:Microsoft.Expression.Interactivity.Media;assembly=Microsoft.Expression.Interactions"
xmlns:ic="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
...
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand Command="{Binding GetTweetsCommand}" CommandParameter="Twitter" />
</i:EventTrigger>
</i:Interaction.Triggers>
此外,只是关于代码隐藏的一般要点:在代码隐藏中拥有与 UI 相关的功能并不是世界上最糟糕的事情!它与您的 ViewModel 是分开的,并且位于合乎逻辑的位置。但是,我发现行为更容易测试。例如,使用继承自的类TargetedTriggerAction
允许故事板由属性更改和控件控制:
public class ImageAnimationTrigger : TargetedTriggerAction<Storyboard>
{
protected override void Invoke(object parameter)
{
if (Target == null)
return;
if (parameter is DependencyPropertyChangedEventArgs)
{
DependencyPropertyChangedEventArgs args = (DependencyPropertyChangedEventArgs)parameter;
if ((bool)args.NewValue)
Target.Begin();
else
Target.Stop();
}
else if (parameter is RoutedEventArgs)
{
RoutedEventArgs args = (RoutedEventArgs)parameter;
if (!(args.OriginalSource as Button).IsEnabled)
Target.Begin();
else
Target.Stop();
}
}
}
我使用这种行为PropertyChangedTrigger
如下:
<i:Interaction.Triggers>
<ic:PropertyChangedTrigger Binding="{Binding Loading}">
<behav:ImageAnimationTrigger TargetName="animStoryboard" />
</ic:PropertyChangedTrigger>
</i:Interaction.Triggers>
正如 Laurent Bugnion 所说,如果需要,请使用代码隐藏!