c - 如何在 Xamarin Forms 平台上应用行为
问题描述
我想对我的 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;
}
}
它不适用于我的项目。我想为标签应用计数器动画。
感谢您的支持。
解决方案
我搜索了 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 - 是否存在更好的方法?)
推荐阅读
- javascript - 在使用 Oracle ADF 时,如何设法检测特定输入文本上的按键
- c++ - 编译 libfluid 示例控制器时对“event_base_del_virtual”的未定义引用
- php - MYSQL查询复制行
- javascript - 未处理的承诺在 15000 毫秒内无法连接数据库
- angular - 如何在 Angular 2 DateTime 选择器上删除/禁用本地时间
- sql - 如何选择介于之间的列日期?“SQL”
- php - 在 WordPress 的 PHP 函数中调用自定义字段
- ios - TabBarController 在以编程方式呈现新视图后消失
- python - 在 PyInstaller 的 SPEC 文件中使用变量
- c - 在堆上使用缓冲区的性能优势 (C)