How to remove the border from a entry control with xamarin forms
Add this class to MainActivity.cs
of Android project :
public class CustomEntryRenderer : EntryRenderer
{
public CustomEntryRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if(e.OldElement == null)
{
Control.Background = null;
var lp = new MarginLayoutParams(Control.LayoutParameters);
lp.SetMargins(0, 0, 0, 0);
LayoutParameters = lp;
Control.LayoutParameters = lp;
Control.SetPadding(0, 0, 0, 0);
SetPadding(0, 0, 0, 0);
}
}
}
and add this line before namespace:
[assembly: ExportRenderer(typeof(Entry), typeof(CustomEntryRenderer))]
then for iOS add this class to Main.cs
:
public class CustomEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
Control.Layer.BorderWidth = 0;
Control.BorderStyle = UITextBorderStyle.None;
}
}
and :
[assembly: ExportRenderer(typeof(Entry), typeof(App1.iOS.CustomEntryRenderer))]
for set this change only for spicial class or custum Entry, just change typeof(Entry)
to typeof(MyEntry)
.
There some properties of controls that you cannot manipulate via Xamarin.Forms, you'll have to implement either an effect or a custom renderer. An effect might well do in your case, but since I'm more proficient with custom renderers, I'll show you how to achieve what you want with a custom renderer.
You'll have to create a class deriving from EntryRenderer
that overrides OnElementChanged
public class CustomEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
this.Control.LeftView = new UIView(new CGRect(0, 0, 8, this.Control.Frame.Height));
this.Control.RightView = new UIView(new CGRect(0, 0, 8, this.Control.Frame.Height));
this.Control.LeftViewMode = UITextFieldViewMode.Always;
this.Control.RightViewMode = UITextFieldViewMode.Always;
this.Control.BorderStyle = UITextBorderStyle.None;
this.Element.HeightRequest = 30;
}
}
First there are some paddings added to the control (it looks quite ugly otherwise) by setting the LeftView
and the RightView
of the native control. Anyway, the more interesting part ist the BorderStyle
by setting this property of the native control you can remove the border of the control.
Last thing you'll have to do is to say Xamarin.Forms to use that renderer. Use the following attribute in the global scope of your file (out of the namespace declaration):
[assembly: ExportRenderer(typeof(Entry), typeof(CustomEntryRenderer))]
If you don't want the style to be applied to all entries, you'll have to define a CustomEntry
class that derives from Entry
in your Xamarin.Forms project change the line presented above to
[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
Please note: This is the iOS implementation, but basically it's the same for Android.