Xamarin 形成 BoxView 动画

Xamarin forms BoxView animation

我正在尝试创建一个闪烁的 BoxView。我创建了一个扩展 BoxView 的 BlinkingBoxView 并添加了 1 个名为 "Blink" 的布尔值 属性。所以我想要的是,每次 Blink 改变并且它的值为 true 时,我想开始闪烁动画,如果值为 false 停止动画。

我是否需要在 C# 代码中执行此操作,或者我是否可以像 WPF 一样仅使用 XAML?

这是我的尝试...

public class BlinkingBoxView : BoxView
{
    public BlinkingBoxView() 
        : base()
    {

    }

    public static readonly BindableProperty BlinkProperty = BindableProperty.Create<BlinkingBoxView, bool>(w => w.Blink, default(bool), BindingMode.TwoWay);

    public bool Blink
    {
        get { return (bool)GetValue(BlinkProperty); }
        set 
        {
            SetValue(BlinkProperty, value);

            var blinkAnimation = new Animation(d => this.FadeTo(0, 750, Easing.Linear)).WithConcurrent(new Animation(d => this.FadeTo(1, 750, Easing.Linear)));

            if (this.Blink)
                this.Animate("Blink", blinkAnimation);
        }
    }
}

您应该使用 OnPropertyChanged 覆盖来捕获属性更改:

public class BlinkingBoxView : BoxView
{
    volatile bool isBlinking;

    public static readonly BindableProperty BlinkProperty = BindableProperty.Create<BlinkingBoxView, bool>(w => w.Blink, default(bool), BindingMode.OneWay);

    public bool Blink
    {
        get
        {
            return (bool)GetValue(BlinkProperty);
        }
        set
        {
            SetValue(BlinkProperty, value);
        }
    }

    public static readonly BindableProperty BlinkDurationProperty = BindableProperty.Create<BlinkingBoxView, uint>(w => w.BlinkDuration, 500, BindingMode.OneWay);

    public uint BlinkDuration
    {
        get
        {
            return (uint)GetValue(BlinkDurationProperty);
        }
        set
        {
            SetValue(BlinkDurationProperty, value);
        }
    }

    protected override void OnPropertyChanged(string propertyName)
    {
        base.OnPropertyChanged(propertyName);

        if (propertyName == BlinkProperty.PropertyName)
        {
            SetBlinking(Blink);
        }
        if (propertyName == BlinkDurationProperty.PropertyName)
        {
            if (isBlinking)
            {
                SetBlinking(false);
                SetBlinking(Blink);
            }
        }
    }

    void SetBlinking(bool shouldBlink)
    {
        if (shouldBlink && !isBlinking)
        {
            isBlinking = true;

            var blinkAnimation = new Animation(((d) => {
                Opacity = d;
            }), 0f, 1f, Easing.SinInOut);

            this.Animate("BlinkingBoxViewBlink", blinkAnimation, length: BlinkDuration, repeat: () => isBlinking);
        }
        else if (!shouldBlink && isBlinking)
        {
            isBlinking = false;
        }
    }
}

您可以在 XAML 中像使用任何其他 View 一样使用它。