我刚开始使用xamarin,我想在单击按钮后更改其颜色,一旦过程完成后应将其恢复为默认颜色,请查看下面的代码。如何在运行时重新渲染按钮?因为命令首先执行,所以我在单击事件中进行了处理。此功能应该适用于Android和iOS。
public class RippleButton : Button
{
private readonly Color _defaultBackgroundColor = Color.FromRgb(255, 87, 34);
private readonly Color _clickedBackgroundColor = Color.FromRgb(76, 175, 80);
public ICommand ClickCommand
{
get { return (ICommand)GetValue(ClickCommandProperty); }
set
{
SetValue(ClickCommandProperty, value);
}
}
public static readonly BindableProperty ClickCommandProperty = BindableProperty.Create(
propertyName: nameof(ClickCommand),
returnType: typeof(ICommand),
declaringType: typeof(RippleButton),
defaultValue: null,
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: OnClickCommandChanged);
private static void OnClickCommandChanged(BindableObject bindable, object oldvalue, object newvalue)
{
}
public RippleButton()
{
const int animationTime = 10;
TextColor = Color.FromRgb(255, 255, 255);
BackgroundColor = _defaultBackgroundColor;
Clicked += async (sender, e) =>
{
var btn = (RippleButton)sender;
BackgroundColor = Color.FromRgb(76, 175, 80);
ClickCommand?.Execute(btn.CommandParameter);
await btn.ScaleTo(1.2, animationTime);
await btn.ScaleTo(1, animationTime);
BackgroundColor = _defaultBackgroundColor;
};
}
private void ChangeColorOfButton()
{
BackgroundColor = _clickedBackgroundColor;
Device.StartTimer(TimeSpan.FromSeconds(0.25), () =>
{
BackgroundColor = _defaultBackgroundColor;
return false;
});
}
}