Partager via


AnimationBehavior

Le AnimationBehavior est un Behavior qui permet d’animer n’importe quel VisualElement auquel il est attaché. Configurer AnimateOnTap sur true ajoute un TapGestureRecognizer au VisualElement et déclenche l'animation associée lorsque ce module de reconnaissance détecte que l'utilisateur a appuyé ou cliqué sur le VisualElement.

La AnimationType propriété doit être définie, les options possibles pour cela sont disponibles dans Animations.

Importante

Les comportements du Kit d’outils de la communauté .NET MAUI ne définissent pas le BindingContext d’un comportement, car ces comportements peuvent être partagés et appliqués à plusieurs contrôles par l’intermédiaire de styles. Pour plus d’informations, consultez les comportements MAUI .NET

Syntaxe

Les exemples suivants montrent comment ajouter le AnimationBehavior à un Label et utiliser le FadeAnimation pour animer une modification de l’opacité.

XAML

Inclusion de l’espace de noms XAML

Pour utiliser le kit de ressources en XAML, le xmlns suivant doit être ajouté à votre page ou vue :

xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"

Par conséquent, les éléments suivants :

<ContentPage
    x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

</ContentPage>

Serait modifié pour inclure la xmlns comme suit :

<ContentPage
    x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">

</ContentPage>

Utilisation d’AnimationBehavior

<ContentPage 
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
    x:Class="CommunityToolkit.Maui.Sample.Pages.Behaviors.AnimationBehaviorPage"
    x:Name="Page">

    <Label Text="Click this Label">
        <Label.Behaviors>
            <toolkit:AnimationBehavior AnimateOnTap="True">
                <toolkit:AnimationBehavior.AnimationType>
                    <toolkit:FadeAnimation Opacity="0.5" />
                </toolkit:AnimationBehavior.AnimationType>
            </toolkit:AnimationBehavior>
        </Label.Behaviors>
    </Label>

</ContentPage>

C#

Le AnimationBehavior peut être utilisé comme suit en C# :

class AnimationBehaviorPage : ContentPage
{
    public AnimationBehaviorPage()
    {
        var label = new Label
        {
            Text = "Click this Label"
        };

        var animationBehavior = new AnimationBehavior
        {
            AnimateOnTap = true, 
            AnimationType = new FadeAnimation
            {
                Opacity = 0.5
            }
        };

        label.Behaviors.Add(animationBehavior);

        Content = label;
    }
}

Balisage C#

Notre CommunityToolkit.Maui.Markup package offre un moyen beaucoup plus concis d’utiliser ceci Behavior en C#.

using CommunityToolkit.Maui.Markup;

class AnimationBehaviorPage : ContentPage
{
    public AnimationBehaviorPage()
    {
        Content = new Label()
            .Text("Click this label")
            .Behaviors(new AnimationBehavior
            {
                AnimateOnTap = true,
                AnimationType = new FadeAnimation
                {
                    Opacity = 0.5
                }
            });
    }
}

La capture d’écran suivante montre l’animationBehavior obtenue sur Android : capture d’écran d’une animationBehavior sur Android

Exemples supplémentaires

Gestion de l’interaction utilisateur

Le AnimationBehavior réagit aux appuis et aux clics de l'utilisateur, il est possible de gérer cette interaction via la propriété Command sur le comportement.

L’exemple suivant montre comment attacher la AnimationBehavior propriété à une Image propriété et la lier Command à une propriété sur un modèle d’affichage.

Afficher

<Image Source="thumbs-up.png" x:Name="ThumbsUpImage">
    <Image.Behaviors>
        <toolkit:AnimationBehavior 
            Command="{Binding ThumbsUpCommand}"
            BindingContext="{Binding Path=BindingContext, Source={x:Reference ThumbsUpImage}, x:DataType=Image}">
            <toolkit:AnimationBehavior.AnimationType>
                <toolkit:FadeAnimation />
            </toolkit:AnimationBehavior.AnimationType>
        </toolkit:AnimationBehavior>
    </Image.Behaviors>
</Image>

Afficher le modèle


public ICommand ThumbsUpCommand { get; }

public MyViewModel()
{
    ThumbsUpCommand = new Command(() => OnThumbsUp())
}

public void OnThumbsUp()
{
    // perform the thumbs up logic.
}

Déclenchement par programmation de l’animation

Il AnimationBehavior permet de déclencher des animations par programmation. AnimateCommand peut être exécuté pour déclencher le type d’animation associé.

L’exemple suivant montre comment ajouter le AnimationBehavior à un Entry, lier AnimatedCommand, puis exécuter la commande à partir d’un modèle de vue.

Afficher

<Entry Placeholder="First name (Required)"
       Text="{Binding FirstName}"
       x:Name="FirstNameEntry">
    <Entry.Behaviors>
        <toolkit:AnimationBehavior 
            AnimateCommand="{Binding TriggerAnimationCommand}"
            BindingContext="{Binding Path=BindingContext, Source={x:Reference FirstNameEntry}, x:DataType=Entry}">
            <toolkit:AnimationBehavior.AnimationType>
                <toolkit:FadeAnimation />
            </toolkit:AnimationBehavior.AnimationType>
        </toolkit:AnimationBehavior>
    </Entry.Behaviors>
</Entry>

Afficher le modèle

private string firstName;

public string FirstName
{
    get => firstName;
    set => SetProperty(ref firstName, value);
}

public ICommand TriggerAnimationCommand { get; set; }

public void Save()
{
    if (string.IsNullOrEmpty(FirstName))
    {
        TriggerAnimationCommand.Execute(CancellationToken.None);
        return;
    }

    // save code.
}

Remarque

La AnimateCommand propriété est en lecture seule et attend un mode de liaison de BindingMode.OneWayToSource. Vous n’avez pas non plus besoin d’affecter une valeur à la propriété de commande dans votre modèle d’affichage (TriggerAnimationCommand dans l’exemple ci-dessus), c’est parce que la liaison affecte la valeur à votre propriété à partir de la valeur créée dans le AnimationBehavior.

Cela permet de déclencher une animation à partir d’un modèle d’affichage.

Déclenchement de l’animation à partir d’événements de contrôle

Il AnimationBehavior fournit les mêmes fonctionnalités sous-jacentes que le EventToCommandBehavior. Grâce à l’utilisation de la EventName propriété, le type d’animation associé peut être déclenché lorsqu’un événement correspondant au nom fourni est déclenché.

Utilisation de l’exemple d’implémentation d’animation suivant :

class SampleScaleToAnimation : BaseAnimation
{
    public double Scale { get; set; }

    public override Task Animate(VisualElement view) => view.ScaleTo(Scale, Length, Easing);
}

L’exemple suivant montre comment affecter deux AnimationBehavior instances à un Entry; une pour déclencher une animation lorsque l’événement Focus est déclenché, et une autre pour déclencher une animation différente lorsque l’événement Unfocused est déclenché.

<Entry Placeholder="Animate on Focused and Unfocused">
    <Entry.Behaviors>
        <toolkit:AnimationBehavior EventName="Focused">
            <toolkit:AnimationBehavior.AnimationType>
                <behaviorPages:SampleScaleToAnimation 
                    Easing="{x:Static Easing.Linear}"
                    Length="100"
                    Scale="1.05"/>
            </toolkit:AnimationBehavior.AnimationType>
        </toolkit:AnimationBehavior>

        <toolkit:AnimationBehavior EventName="Unfocused">
            <toolkit:AnimationBehavior.AnimationType>
                <behaviorPages:SampleScaleToAnimation 
                    Easing="{x:Static Easing.Linear}"
                    Length="100"
                    Scale="1"/>
            </toolkit:AnimationBehavior.AnimationType>
        </toolkit:AnimationBehavior>
    </Entry.Behaviors>
</Entry>

Exemples

Vous trouverez un exemple de ce comportement en action dans l’exemple d’application .NET MAUI Community Toolkit.

API (Interface de Programmation d'Applications)

Vous pouvez trouver le code source de AnimationBehavior dans le dépôt GitHub du .NET MAUI Community Toolkit .