【发布时间】:2012-07-03 20:46:05
【问题描述】:
在图像上运行动画后 我从这里得到的:Animate image in a button 我希望能够打开和关闭动画,具体取决于 从外部点击按钮,即从 ViewModel
所以我在 Bahavior 中添加了一个新的 DependencyProperty(这里需要的所有东西)
public static readonly DependencyProperty IsShakingProperty =
DependencyProperty.Register(IsShakingName,
typeof(bool),
typeof(ShakeBehavior),
new PropertyMetadata(DefaultIsShaking));
我已向我的 ViewModel 添加了一个新的公共属性
public bool IsShaking { get; set; }
但是我可以做些什么来打开和关闭动画,这取决于 ViewModel 属性设置为 true 还是 false? (我想控制动画 点击按钮)
这是我认为相关的一些代码
private Timeline CreateAnimationTimeline()
{
DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames();
animation.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("(0).(1)", UIElement.RenderTransformProperty, RotateTransform.AngleProperty));
int keyFrameCount = 8;
double timeOffsetInSeconds = 0.25;
double totalAnimationLength = keyFrameCount * timeOffsetInSeconds;
double repeatInterval = RepeatInterval;
bool isShaking = IsShaking;
// Can't be less than zero and pointless to be less than total length
if (repeatInterval < totalAnimationLength)
repeatInterval = totalAnimationLength;
animation.Duration = new Duration(TimeSpan.FromSeconds(repeatInterval));
int targetValue = 12;
for (int i = 0; i < keyFrameCount; i++)
animation.KeyFrames.Add(new LinearDoubleKeyFrame(i % 2 == 0 ? targetValue : -targetValue, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(i * timeOffsetInSeconds))));
animation.KeyFrames.Add(new LinearDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(totalAnimationLength))));
return animation;
}
这是我的 XAML 的一部分:
<ListBox.ItemTemplate>
<DataTemplate>
<Button Focusable="False" Command="{Binding ClickToolCommand}" Grid.Row="{Binding Path=Row}" Grid.Column="{Binding Path=Col}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
<Image Source="myImage.png" Grid.Row="{Binding Path=Row}" Grid.Column="{Binding Path=Col}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
<i:Interaction.Behaviors>
<local:ShakeBehavior RepeatInterval="1" SpeedRatio="3.0" IsShaking="{Binding Path=IsShaking}"/>
</i:Interaction.Behaviors>
</Image>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
也许 DataTrigger 可以提供帮助,正如其他 SO 中指出的那样,但我的 XAML 中没有情节提要,因为我有一个自定义 Behavior
任何意见都非常感谢!
【问题讨论】:
标签: c# wpf xaml animation mvvm