gpt4 book ai didi

xamarin.forms - 更改 Xamarin.Forms 按钮单击的颜色

转载 作者:行者123 更新时间:2023-12-01 19:35:44 25 4
gpt4 key购买 nike

我正在开发 Xamarin.Forms UWP 应用程序,我想在按下按钮时更改按钮的背景颜色。我一直在网上搜索,我能找到的最直接的方法是:

 private void Button_OnClicked(object s, EventArgs e)
{
var b = (Button) s;
var originalColour = b.BackgroundColor;
b.BackgroundColor = Color.DarkOrange;
Device.StartTimer(TimeSpan.FromSeconds(0.25), () =>
{
b.BackgroundColor = originalColour;
return false;
});
}

但是,就我个人而言,我不太喜欢这种方法。如何才能做得更好?

最佳答案

EventTrigger XAML中的解决方案:

MyAssembly中实现以下内容,例如包含 App.xaml 的可移植程序集:

using Xamarin.Forms;

namespace MyNamespace
{
public class ButtonTriggerAction : TriggerAction<VisualElement>
{
public Color BackgroundColor { get; set; }

protected override void Invoke(VisualElement visual)
{
var button = visual as Button;
if (button == null) return;
if (BackgroundColor != null) button.BackgroundColor = BackgroundColor;
}
}
}

XAML:

xmlns:local="clr-namespace:MyNamespace;assembly=MyAssembly"
...
<Button Text="EventTrigger">
<Button.Triggers>
<EventTrigger Event="Pressed">
<local:ButtonTriggerAction BackgroundColor="Red" />
</EventTrigger>
<EventTrigger Event="Released">
<local:ButtonTriggerAction BackgroundColor="Default" />
</EventTrigger>
</Button.Triggers>
</Button>

关于xamarin.forms - 更改 Xamarin.Forms 按钮单击的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48852455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com