Reputation: 61
Migrating from Xamarin.Forms to NET.MAUI I need a custom entry control (custom renderer), in order to detect keyboard's backspace key event. I have four entries with 1 digit each (4 digits pins), and when the user focus on an empty text entry and presses backspace, I need to change focus in the previous digit. I used the following implementation in Xamarin.Forms, but I need to migrate in NET.MAUI.
Android
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace Test.Droid.CustomRenderer { public class CustomEntryRenderer : EntryRenderer {
public CustomEntryRenderer(Context context) : base(context) {
}
public override bool DispatchKeyEvent(KeyEvent e) {
if (e.Action == KeyEventActions.Down) {
if (e.KeyCode == Keycode.Del) {
if (string.IsNullOrWhiteSpace(Control.Text)) {
CustomEntry entry = (CustomEntry)Element;
entry.OnBackspacePressed();
}
}
}
return base.DispatchKeyEvent(e);
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Entry> e) {
base.OnElementChanged(e);
}
}
}
iOS
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace Test.iOS.CustomRenderers {
public class CustomEntryRenderer : EntryRenderer, IUITextFieldDelegate {
IElementController ElementController => Element as IElementController;
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) {
if (Element == null) {
return;
}
var entry = (CustomEntry)Element;
var textField = new UIBackwardsTextField();
textField.EditingChanged += OnEditingChanged;
textField.OnDeleteBackward += (sender, a) => {
entry.OnBackspacePressed();
};
SetNativeControl(textField);
base.OnElementChanged(e);
}
void OnEditingChanged(object sender, EventArgs eventArgs) {
ElementController.SetValueFromRenderer(Entry.TextProperty, Control.Text);
}
}
public class UIBackwardsTextField : UITextField {
// A delegate type for hooking up change notifications.
public delegate void DeleteBackwardEventHandler(object sender, EventArgs e);
// An event that clients can use to be notified whenever the
// elements of the list change.
public event DeleteBackwardEventHandler OnDeleteBackward;
public void OnDeleteBackwardPressed() {
if (OnDeleteBackward != null) {
OnDeleteBackward(null, null);
}
}
public UIBackwardsTextField() {
BorderStyle = UITextBorderStyle.RoundedRect;
ClipsToBounds = true;
}
public override void DeleteBackward() {
base.DeleteBackward();
OnDeleteBackwardPressed();
}
}
}
And custom control
namespace Test.CustomControls {
public class CustomEntry : Entry {
public delegate void BackspaceEventHandler(object sender, EventArgs e);
public event BackspaceEventHandler OnBackspace;
public CustomEntry() { }
public void OnBackspacePressed() {
if (OnBackspace != null) {
OnBackspace(null, null);
}
}
}
}
Upvotes: 1
Views: 701