Issue
So i do some validations on my entries and i would like to change the color to red when the value is invalid.
Is there a way to do this in xamarin right now ?
I know that there's renderer to change the color permanently but i just want to change it based on a condition and leave it black when everything is ok.
Thank you.
Solution
You could overwrite OnElementPropertyChanged
method in your CustomRenderer to achieve this.
For example:
for Android:
[assembly: ExportRenderer(typeof(Entry), typeof(UnderLineEntry))]
namespace EntryCa.Droid
{
class UnderLineEntry : EntryRenderer
{
public UnderLineEntry(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control == null || e.NewElement == null) return;
Control.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Black);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Entry.TextProperty.PropertyName)
{
if (Control.Text.Length > 6) //this is your condition(For example, here is the length of the text content)
{
Control.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Red);
}
else
{
Control.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Black);
}
}
}
}
}
the ios is the similar to Android,also change it in the OnElementPropertyChanged
method,if you want i could give you an example.
for ios.
[assembly: ExportRenderer(typeof(Entry), typeof(MyEntryRenderer))]
namespace EntryCa.iOS
{
public class MyEntryRenderer : EntryRenderer
{
private CALayer _line;
public override void LayoutSubviews()
{
base.LayoutSubviews();
Control.BorderStyle = UITextBorderStyle.None;
_line = new CALayer
{
BackgroundColor = UIColor.Black.CGColor,
Frame = new CGRect(0, Frame.Height, Frame.Width, 1f)
};
Control.Layer.AddSublayer(_line);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Entry.TextProperty.PropertyName)
{
if (Control.Text.Length > 6)
{
_line.RemoveFromSuperLayer();
_line = new CALayer
{
BackgroundColor = UIColor.Red.CGColor,
Frame = new CGRect(0, Frame.Height, Frame.Width, 1f)
};
Control.Layer.AddSublayer(_line);
}
else
{
_line.RemoveFromSuperLayer();
_line = new CALayer
{
BackgroundColor = UIColor.Black.CGColor,
Frame = new CGRect(0, Frame.Height, Frame.Width, 1f)
};
Control.Layer.AddSublayer(_line);
}
}
}
}
}
Answered By - Leo Zhu - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.