xaml - 使用 MVVM 时,在 View 中为对象设置动画的最佳方法是什么?
问题描述
我有一个简单的 Xamarin Forms 应用程序。我正在使用棱镜表格。当旧值和新值不相等时,我想在 View 中使用基本淡入淡出动画为 Label 设置动画。在 View 中为对象设置动画的最佳方法是什么?先感谢您。
MainPageViewModel.cs
public class MainPageViewModel : BindableBase
{
public HomePageViewModel()
{
Title = "First";
ChangeTitle();
}
private async void ChangeTitle()
{
await Task.Delay(5000);
if(Title == "First")
{
Title = "Second";
}
else
{
Title = "First";
}
ChangeTitle();
}
private string title;
public string Title
{
get { return title; }
set { SetProperty(ref title, value); }
}
}
主页.xml
<ContentPage
x:Class="SmapleApp.Views.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="http://prismlibrary.com"
prism:ViewModelLocator.AutowireViewModel="True"
Title="Main Page">
<Label Text="{Binding Title}" />
</ContentPage>
解决方案
动画逻辑应仅限于视图。推荐的选项是使用附加的行为来侦听文本更改并相应地为关联的标签设置动画。
public class FadingLabelAnimationBehavior : Behavior<Label>
{
private Label _associatedObject;
private uint DesiredDuration { get; set; } = 750;
protected override void OnAttachedTo(Label bindable)
{
base.OnAttachedTo(bindable);
_associatedObject = bindable;
_associatedObject.PropertyChanged += OnTextChangedHandler;
}
private async void OnTextChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == Label.TextProperty.PropertyName)
{
_associatedObject.Opacity = 0f;
await _associatedObject.FadeTo(1f, DesiredDuration);
}
}
protected override void OnDetachingFrom(Label bindable)
{
_associatedObject = null;
base.OnDetachingFrom(bindable);
_associatedObject.PropertyChanged -= OnTextChangedHandler;
}
}
用法:
<Label Text="{Binding Title}" ... >
<Label.Behaviors>
<local:FadingLabelAnimationBehavior />
</Label.Behaviors>
</Label>
更多探索选项:
推荐阅读
- conv-neural-network - 暗网中YOLOv2网络中absolute、jitter、rescore和bias_match有什么用?
- ios - UIKit Dynamics 和 UIKit Animation 有什么区别?
- android - 从 OnItemSelectedListener 调用值
- vue.js - vuejs 搜索过滤器“TypeError:无法读取 null 的属性‘过滤器’”
- c++ - C++ Json 库构建
- concourse - 在 Concourse 中执行 hello world 时出错
- c - C 语言 - 添加产品的数字(即,不是产品本身)
- javascript - 如何在 Axios Mock 适配器中使用路径参数
- exception - setState() 或 markNeedsBuild() 在小部件树被锁定时调用 >。改变状态时
- spring-boot - th:text 中的 thymleaf 连接正在覆盖先前的值