you can achieve this in a simple way by creating a very simple user control that inherits from Image.
Here is the code for "MyImage":
public class MyImage : Image
{
public static readonly RoutedEvent ImageUpdatedEvent =
EventManager.RegisterRoutedEvent("ImageUpdated", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyImage));
public event RoutedEventHandler ImageUpdated
{
add { this.AddHandler(ImageUpdatedEvent, value); }
remove { this.RemoveHandler(ImageUpdatedEvent, value); }
}
public static readonly DependencyProperty MyImageSourceProperty = DependencyProperty.Register(
"MyImageSource",
typeof(ImageSource),
typeof(MyImage),
new PropertyMetadata(null, new PropertyChangedCallback(OnMyImageSourceChanged)));
public ImageSource MyImageSource
{
get { return (ImageSource)GetValue(MyImageSourceProperty); }
set
{
Source = value;
SetValue(MyImageSourceProperty, value);
}
}
private static void OnMyImageSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
MyImage img = obj as MyImage;
img.Source = args.NewValue as ImageSource;
img.RaiseEvent(new RoutedEventArgs(ImageUpdatedEvent));
}
}
The MyImage control has its own image source property and its own routed event called "ImageUpdated", which later triggers the storyboard. I simplified your image code:
<Button Click="Button_Click" Grid.Row="0">Set Image through view model</Button>
<local:MyImage Grid.Row="1" x:Name="pic" MyImageSource="{Binding MySource}">
<Image.Triggers>
<EventTrigger RoutedEvent="local:MyImage.ImageUpdated">
<BeginStoryboard >
<Storyboard >
<DoubleAnimation Storyboard.TargetProperty="(Image.Opacity)" From="0" To="1" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Image.Triggers>
</local:MyImage>
, INotifyPropertyChanged:
private void Button_Click(object sender, RoutedEventArgs e)
{
int randomValue = new Random(DateTime.Now.Second).Next(0, 2);
if (randomValue == 0)
{
_viewModel.MySource = new BitmapImage(new Uri(@"test.bmp", UriKind.Relative));
}
else
{
_viewModel.MySource = new BitmapImage(new Uri(@"test2.bmp", UriKind.Relative));
}
}
MyImage :
public ImageSource MySource
{
get { return _mySource; }
set
{
_mySource = value;
RaisePropertyChanged("MySource");
}
}
.
,
Jan