在我的Xamarin.forms应用程序中,我有两个按钮。我需要实现以下目标......
答案 0 :(得分:2)
您必须设计自定义渲染器才能实现此目的。
在您的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中创建渲染器:
例如:Android:
[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"
然后在UI中,您可以访问如下:
CustomButton.OnPressed += (sender, args) =>
{
//Your code
};
CustomButton.OnReleased += (sender, args) =>
{
//Your code.
};
希望这有帮助!!
答案 1 :(得分:0)
您可以在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;
}
};