如果在属性绑定发生变化时如何开始故事板?
我的图像来源每5秒更改一次(在我的ViewModel中),我希望在图像发生变化时播放故事板。
<Grid>
<Image x:Name="image" Source="{Binding CurrentImage}"/>
</Grid>
答案 0 :(得分:3)
通常会为Source
属性更改时触发的事件添加EventTrigger。不幸的是,Image控件没有定义这样的事件,所以你必须通过派生自Image:
public class MyImage : Image
{
public static readonly RoutedEvent SourceChangedEvent = EventManager.RegisterRoutedEvent(
"SourceChanged", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(MyImage));
static MyImage()
{
Image.SourceProperty.OverrideMetadata(typeof(MyImage), new FrameworkPropertyMetadata(SourcePropertyChanged));
}
public event RoutedEventHandler SourceChanged
{
add { AddHandler(SourceChangedEvent, value); }
remove { RemoveHandler(SourceChangedEvent, value); }
}
private static void SourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Image image = obj as Image;
if (image != null)
{
image.RaiseEvent(new RoutedEventArgs(SourceChangedEvent));
}
}
}
现在您可以在EventTrigger中使用SourceChanged
事件:
<local:MyImage Source="{Binding Image}">
<local:MyImage.Triggers>
<EventTrigger RoutedEvent="local:MyImage.SourceChanged">
<BeginStoryboard>
<Storyboard>
...
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</local:MyImage.Triggers>
</local:MyImage>
答案 1 :(得分:1)
我认为您最好向ViewModel添加一个事件,并在源更改时启动它。当然,在该事件上使用EventTrigger来执行Storyboard。