您是否嘗試過Xamarin論壇鏈接here的代碼。我沒有親自嘗試過,但它看起來可以用來做你想做的事情,包括使用動態顏色。也許這樣的事情(我寫了一些從內存中的代碼,所以讓我知道,如果它不工作):
形式:
public class FancyButton : Button {
/// <summary>
/// The color pressed down color property.
/// </summary>
public static readonly BindableProperty PressedDownColorProperty = BindableProperty.Create(nameof(PressedDownColor), typeof(Color), typeof(FancyButton), default(Color));
/// <summary>
/// Gets or sets the pressed down color.
/// </summary>
/// <value>The color to change to when the button is pressed down string.</value>
public Color PressedDownColor {
get { return (Color)GetValue(PressedDownProperty); }
set { SetValue(PressedDownProperty, value); }
}
}
的Droid:
[assembly: ExportRenderer(typeof(App2.FancyButton), typeof(FancyButtonAndroid))]
namespace App2.Droid {
public class FancyButtonAndroid : ButtonRenderer {
private Color _pressedDownColor;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e) {
base.OnElementChanged(e);
Android.Widget.Button thisButton = Control as Android.Widget.Button;
FancyButton formsButton = (FancyButton)Element;
_pressedDownColor = formsButton.PressedDownColor;
thisButton.Touch += (object sender, Android.Views.View.TouchEventArgs e2) => {
if (e2.Event.Action == MotionEventActions.Down) {
thisButton.SetBackgroundColor(_pressedDownColor.ToAndroid());
} else if (e2.Event.Action == MotionEventActions.Up) {
thisButton.SetBackgroundColor(Xamarin.Forms.Color.Default.ToAndroid());
}
};
}
/// <summary>
/// Raises the element property changed event.
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">The event arguments</param>
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {
base.OnElementPropertyChanged(sender, e);
FancyButton formsButton = Element as FancyButton;
if(formsButton != null && e.PropertyName == FancyButton.PlaceholderProperty.PropertyName) {
_pressedDownColor = formsButton.PressedDownColor;
}
}
}
}
哎呀,只是想出了你的意思是。還有一個問題,我的drawable可以是顏色而不是圖像嗎?如果我的按鈕的顏色,我希望它成爲當前頁面的背景顏色......所以它是一種動態顏色?這是行不通的。謝謝! –
@Cheesebaron - 它看起來像你的答案是適用於Android的Xamarin,而不是Xamarin Forms。這是問題所要求的嗎?如果是這樣,我們需要刪除Xamarin.Forms標籤,當然? –
他有Android標籤。因此Android的答案。他說他有一個自定義渲染器,因此他可以在自定義渲染器中使用此代碼來獲得所需的效果。 – Cheesebaron