[英]Change background color of button on click and hold in Xamarin.forms
为了实现这一点,您必须设计一个自定义渲染器。
在您的 Core/PCL 项目中创建一个按钮类:
public class CustomButton : Button
{
public event EventHandler OnPressed;
public event EventHandler OnReleased;
public void OnPressed()
{
OnPressed?.Invoke(this, EventArgs.Empty);
}
public void OnReleased()
{
OnReleased?.Invoke(this, EventArgs.Empty);
}
}
然后在你的 iOS 和 Android 中创建 Renderer :
例如:安卓:
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace yourproject.Droid.Renderer
{
public class CustomButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
var customRendererButton = e.NewElement as CustomButton;
var control = Control as Android.Widget.Button;
control.Touch += (object sender, TouchEventArgs args) =>
{
if (args.Event.Action == MotionEventActions.Up)
{
customRendererButton.OnReleased();
}
else if (args.Event.Action == MotionEventActions.Down)
{
customRendererButton.OnPressed();
}
};
}
}
}
IOS:
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace yourproject.iOS.Renderer
{
public class CustomButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
var customRendererButton = e.NewElement as CustomButton;
var control = Control as UIButton;
control.TouchDown += delegate
{
customRendererButton.OnPressed();
};
thisButton.TouchUpInside += delegate
{
customRendererButton.OnReleased();
};
}
}
}
然后在您的 xaml 文件中,将按钮链接到 custombutton :
在 xaml 的主标记中将命名空间定义为自定义:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:custom="clr-namespace:yourproject.Core.namespaceofCustomButton;assembly=yourproject.Core">
然后,
<custom:CustomButton x:Name="CustomButton"
然后在用户界面中,您可以访问如下:
CustomButton.OnPressed += (sender, args) =>
{
//Your code
};
CustomButton.OnReleased += (sender, args) =>
{
//Your code.
};
希望这有帮助!!
您可以在 xaml 中使用x:Name="myButton"
然后:
myButton.Touch += (object sender, TouchEventArgs args) =>
{
if (args.Event.Action == MotionEventActions.Up)
{
myButton.BackgroundColor = Color.Blue;
}
else if (args.Event.Action == MotionEventActions.Down)
{
myButton.BackgroundColor = Color.Red;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.