如何在 Xamarin Forms 平台上应用行为

How to Apply Behaviors on Xamarin Forms Platform

我想要数字 counterup/down 动画我的 xamarin 表单应用程序。我找到了代码示例 here

但是我还没有申请。我如何应用此行为 class Xamarin Forms 标签控件。

我试过这段代码但没有用。

 <Label x:Name="lblScore"  FontSize="24"  TextColor="Black" Text="{Binding Number}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand">
                        <Label.Behaviors>
                            <controls:NumericTextAnimationBehavior Value="{Binding Number}"/>
                        </Label.Behaviors>
                    </Label>

代码隐藏:

public partial class ProfilePage : ContentPage
{
    public string Number { get; set; }
    public ProfilePage()
    {
        InitializeComponent();

        this.BindingContext = this;

        lblScore.Behaviors.Add(new NumericTextAnimationBehavior());
    }

    private void btnSetRandom_Clicked(object sender, EventArgs e)
    {
        Random randomizer = new Random();
        Number = randomizer.Next(1, 9999).ToString();

        lblScore.Text = Number;

    }
}

它不适用于我的项目。我想为标签应用计数器动画。

感谢您的支持。

我搜索了 INotifyPropertyChanged 模式并解决了它。

型号:

public class ScoreViewModel : INotifyPropertyChanged
{
    // boiler-plate
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    // props
    private string number;
    public string Number
    {
        get { return number; }
        set { SetField(ref number, value, "Number"); }
    }
}

页数:

public partial class ProfilePage : ContentPage
{
    ScoreViewModel scoreViewModel = new ScoreViewModel();
    public ProfilePage()
    {
        InitializeComponent();

        lblScore.BindingContext = scoreViewModel;
    }

    private void btnSetRandom_Clicked(object sender, EventArgs e)
    {
        Random randomizer = new Random();
        scoreViewModel.Number = randomizer.Next(9999, 99999).ToString();

    }
}

Xaml:

 <Label x:Name="lblScore"  FontSize="24" Text="{Binding Number}">
    <Label.Behaviors>
        <controls:NumericTextAnimationBehavior Value="{Binding Number}"/>
    </Label.Behaviors>
</Label>

如果您想深入了解 INotifyPropertyChanged 实现,请查看此处 (Implementing INotifyPropertyChanged - does a better way exist?)