1

我想对我的 xamarin 表单应用程序进行数字计数器向上/向下动画。我在这里找到了代码示例

但是我没有申请。我如何应用此行为类 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;

    }
}

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

感谢您的支持。

4

1 回答 1

0

我搜索了 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();

    }
}

xml:

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

如果您想深入了解 INotifyPropertyChanged 的​​实现,请看这里(Implementing INotifyPropertyChanged - 是否存在更好的方法?

于 2019-11-12T13:00:44.193 回答