Geo*_*iev 5 xamarin.forms uwp xamarin.uwp
我正在开发 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;
});
}
Run Code Online (Sandbox Code Playgroud)
但是,就我个人而言,我不太喜欢这种方法。这如何做得更好?
Ben*_*enl 10
XAML 中的EventTrigger解决方案:
在 中实现以下内容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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
一种更自然、更清洁的方法是使用 VisualStateManager
<Button Text="Click Me!">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="Green" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="Red" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Button>
Run Code Online (Sandbox Code Playgroud)
你可以在这里阅读更多信息。
| 归档时间: |
|
| 查看次数: |
7007 次 |
| 最近记录: |