How to implement animation when Image source chang

2019-08-23 10:16发布

问题:

I am working on xamarin.forms and want to start an animation when the image source are changed.

           <ListView >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Image Source="{Binding FavoriteImage}" x:Name="favoriteImage">
                                 <Image.GestureRecognizers>
                                     TapGestureRecognizer Command="{Binding Source={x:Reference CurrentPage},Path=BindingContext.ClickLikedCommand}"  CommandParameter="{Binding .}" NumberOfTapsRequired="1"/>
                                 </Image.GestureRecognizers>
                            </Image>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

The image source is bind to an variable in the ViewModel and will be changed if user click the image and get a successful response from server. Then the new Image will be shown with some custom animation, so where can I trigger this animation since the image source changed? I have read the "Behavior" and "Trigger" tutorial online, It seems it could trigger an animation by an event, but Image class has not such an "SourceChanged" event.

回答1:

You can use the OnPropertyChanged method:

public class ExImage : Image
{
    protected override void OnPropertyChanged(string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);

        if (propertyName == nameof(Source))
            Device.BeginInvokeOnMainThread(async () =>
            {
                await this.ScaleTo(1.2);
                await this.ScaleTo(1);
            });
    }
}