Xamarin.Forms How to add Behaviors in code - xamarin

What I am trying to achieve is limiting the input of an Entry field to two character via code and not XAML
This can be achieved in XAML using the below:
<Entry.Behaviors>
<local:NumberValidatorBehavior x:Name="ageValidator" />
<local:MaxLengthValidator MaxLength="2"/>
I assume I will need to do something like this but I'm not quite sure how to add the required behaviour property
entry.Behaviors.Add(new MyBehavior())
Edit Answer
After adding the MaxLengthValidator class listed below and calling it using the proposed method by #Rui Marinho my code is working as expected.
public class MaxLengthValidator : Behavior<Entry>
{
public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidator), 0);
public int MaxLength
{
get { return (int)GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += bindable_TextChanged;
}
private void bindable_TextChanged(object sender, TextChangedEventArgs e)
{
if (e.NewTextValue.Length > 0 && e.NewTextValue.Length > MaxLength)
((Entry)sender).Text = e.NewTextValue.Substring(0, MaxLength);
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= bindable_TextChanged;
}
}

entry.Behaviors.Add(new MaxLengthValidator { MaxLength = 2 });

Related

How to validate an email "Entrycell" in xamarin forms

I have an email entrycell inside my tableview. I need to do behavior validation for that.I have done this for entry.
How can i do the same for entrycell?
My current code to an entry is given below.
/*
public class EmailValidatorBehavior : Behavior<Entry>
{
protected override void OnAttachedTo(Entry bindable)
{
base.OnAttachedTo(bindable);
bindable.TextChanged += HandleTextChanged;
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
var email = e.NewTextValue;
var emailpattern = #"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
var emailentry = sender as Entry;
if (Regex.IsMatch(email, emailpattern))
{
emailentry.BackgroundColor = Color.Transparent;
}
else
{
emailentry.BackgroundColor = Color.Red;
}
}
protected override void OnDetachingFrom(Entry bindable)
{
base.OnDetachingFrom(bindable);
bindable.TextChanged -= HandleTextChanged;
}
}
*/
maybe you could custom viewcell with laber and entry,then add the behavior to the entry,or you could use CustomRender like this(a simple example for android, not sure if it meets your needs,ios is similar to thisto this):
[assembly: ExportRenderer(typeof(EntryCell), typeof(MyEntryCellRenderer))]
namespace App18.Droid
{
class MyEntryCellRenderer : EntryCellRenderer
{
string emailpattern = #"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
EditText _view;
protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
{
var cell = base.GetCellCore(item, convertView, parent, context) as EntryCellView;
cell.EditText.AfterTextChanged += EditText_AfterTextChanged;
return cell;
}
private void EditText_AfterTextChanged(object sender, Android.Text.AfterTextChangedEventArgs e)
{
if (Regex.IsMatch(((EditText)sender).Text, emailpattern))
{
((EditText)sender).SetTextColor(Android.Graphics.Color.Green);
}
else
{
((EditText)sender).SetTextColor(Android.Graphics.Color.Red);
}
}
}
}
You can add your Regular Expression on top of the declaration the Email property in your Model, than the property have value only if respect the regular expression condition.

Xamarin Forms Button Command doesn't fire after adding button effect

I have a button like this:
<Button Margin="0,20,0,0" Command="{Binding OnSkip}" BackgroundColor="{StaticResource Primary}" CornerRadius="2"
Text="Terms and Conditions of Use" VerticalOptions="End" TextColor="White">
<Button.Effects>
<effects1:ButtonClickEffect></effects1:ButtonClickEffect>
</Button.Effects>
</Button>
Upon adding the button effect inside the button, the 'OnSkip' command no longer fires and I'm not sure why.
The button click effect code is implemented as follows:
public class AndroidButtonClickEffect : PlatformEffect
{
protected override void OnAttached()
{
this.Control.Touch += this.Control_Touch;
}
private void Control_Touch(object sender, Android.Views.View.TouchEventArgs e)
{
if (e.Event.Action == MotionEventActions.Down)
{
this.SetColor(Android.Graphics.Color.Blue);
}
else if (e.Event.Action == MotionEventActions.Up)
{
this.SetColor(Android.Graphics.Color.LightBlue);
}
}
private void SetColor(Android.Graphics.Color color)
{
this.Control.SetBackgroundColor(color);
}
protected override void OnDetached()
{
this.Control.Touch -= this.Control_Touch;
}
}
Removing the button effect causes the command to fire again. Why does the button effect interfere with the command firing? Is there a way I can get the effect to invoke the desired command (generically so I can reuse the effect)?
Thanks.
In the main project, I added the following class, which binds the Command:
public class ButtonClickEffect : RoutingEffect
{
public ButtonClickEffect() : base("Framework.ButtonClickEffect") { }
public static readonly BindableProperty CommandProperty =
BindableProperty.Create("Command", typeof(ICommand), typeof(ButtonClickEffect));
public static ICommand GetCommand(BindableObject view)
{
return (ICommand)view.GetValue(CommandProperty);
}
public static void SetCommand(BindableObject view, ICommand value)
{
view.SetValue(CommandProperty, value);
}
public static readonly BindableProperty CommandParameterProperty =
BindableProperty.CreateAttached("CommandParameter", typeof(object),
typeof(ButtonClickEffect), (object)null);
public static object GetCommandParameter(BindableObject view)
{
return view.GetValue(CommandParameterProperty);
}
public static void SetCommandParameter(BindableObject view, object value)
{
view.SetValue(CommandParameterProperty, value);
}
}
The Android implementation was implemented as follows:
[assembly:ResolutionGroupName("Framework")]
[assembly:ExportEffect(typeof(AndroidButtonClickEffect), "ButtonClickEffect")]
namespace Framework.Droid.Effects
{
public class AndroidButtonClickEffect : PlatformEffect
{
protected override void OnAttached()
{
Control.Touch += Control_Touch;
}
private void Control_Touch(object sender, Android.Views.View.TouchEventArgs e)
{
if (e.Event.Action == MotionEventActions.Down)
{
SetColor(Color.LightBlue);
}
else if (e.Event.Action == MotionEventActions.Up)
{
SetColor(Color.Blue);
}
var command = ButtonClickEffect.GetCommand(Element);
command?.Execute(ButtonClickEffect.GetCommandParameter(Element));
}
private void SetColor(Color color)
{
Control.SetBackgroundColor(color);
}
protected override void OnDetached()
{
Control.Touch -= Control_Touch;
}
}
}
I then removed the 'Command' property from my button and replaced it as follows:
<Button Margin="0,20,0,0" BackgroundColor="{StaticResource Primary}" CornerRadius="2"
Text="Terms and Conditions of Use" VerticalOptions="End" TextColor="White"
effects1:ButtonClickEffect.Command="{Binding OnSkip}" effects1:ButtonClickEffect.CommandParameter="{Binding .}">
<Button.Effects>
<effects1:ButtonClickEffect></effects1:ButtonClickEffect>
</Button.Effects>
</Button>
In all honesty, the command binding is a lot more awkward now (all this code just to get a simple button effect), but the important thing is that it now works. Now I need to work out how implement for iOS.
Credit from here for the answer and whoever posted this URL as an answer (it got deleted).

Xamarin Forms Password and Confirm Password Validation

I have a Xamarin Forms application in which I have a registration form in which I need to validate Password and Confirm Password fields should be same.
Is there any way to implement this using Xamarin Behaviour?
I have already implemented Xamarin Behaviour for Required Field validation and Email Regex validation like this below-
public class RequiredValidatorBehavior : Behavior<Entry>
{
static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(RequiredValidatorBehavior), false);
static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
public bool IsValid
{
get { return (bool)base.GetValue(IsValidProperty); }
private set { base.SetValue(IsValidPropertyKey, value); }
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.Unfocused += HandleFocusChanged;
base.OnAttachedTo(bindable);
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.Unfocused -= HandleFocusChanged;
base.OnDetachingFrom(bindable);
}
void HandleFocusChanged(object sender, FocusEventArgs e)
{
IsValid = !string.IsNullOrEmpty (((Entry)sender).Text);
}
}
Implementation of Behaviour in XAML Content Page-
<Entry x:Name="password" Placeholder="New Password">
<Entry.Behaviors>
<local:RequiredValidatorBehavior x:Name="passwordValidator"/>
</Entry.Behaviors>
</Entry>
The problem is - I am new in Xamarin development and have no idea how can I get the value of both Password and Confirm Password fields in Behaviour so that I can compare them. I do not wish to compare them on click of button when the form is submitted, fields should be compared while the user is typing in the fields. Any code, help or guidance is appreciable.
https://forums.xamarin.com/discussion/34695/xaml-how-do-you-pass-a-control-view-reference-into-a-behavior
This will help you.
You will use Compare Validator behavior for this as following.
<behaviors:CompareValidator x:Name="ComparePasswordsValidator"
CompareToEntry="{Binding Source={x:Reference PasswordEntry}}" />
Finally The Solution:
XAML-
<Entry x:Name="password" Placeholder="New Password" IsPassword="true">
<Entry.Behaviors>
<local:RequiredValidatorBehavior x:Name="passwordValidator"/>
</Entry.Behaviors>
</Entry>
<Entry x:Name="confirmPassword" Placeholder="Confirm Password" IsPassword="true">
<Entry.Behaviors>
<local:ConfirmPasswordBehavior x:Name="confirmPasswordBehavior" CompareToEntry="{Binding Source={x:Reference password}}" />
</Entry.Behaviors>
</Entry>
BEHAVIOR-
public class ConfirmPasswordBehavior : Behavior<Entry>
{
static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(ConfirmPasswordBehavior), false);
public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
public static readonly BindableProperty CompareToEntryProperty = BindableProperty.Create("CompareToEntry", typeof(Entry), typeof(ConfirmPasswordBehavior), null);
public Entry CompareToEntry
{
get { return (Entry)base.GetValue(CompareToEntryProperty); }
set { base.SetValue(CompareToEntryProperty, value); }
}
public bool IsValid
{
get { return (bool)base.GetValue(IsValidProperty); }
private set { base.SetValue(IsValidPropertyKey, value); }
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
var password = CompareToEntry.Text;
var confirmPassword = e.NewTextValue;
IsValid = password.Equals (confirmPassword);
}
}
I've make some changes on Punnet answer:
First, to fix the null exception on HandleTextChanged that was thrown when the comparable string was null
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
string theBase = CompareToEntry.Text;
string confirmation = e.NewTextValue;
// here is the change
IsValid = (bool)theBase?.Equals(confirmation);
((Entry)sender).TextColor = IsValid ? Color.Green : Color.Red;
}
And the second was to check if the comparable string was changed after the validation becomes true.
void baseValue_changed(object sender, TextChangedEventArgs e)
{
IsValid = (bool)((Entry)sender).Text?.Equals(thisEntry.Text);
thisEntry.TextColor = IsValid ? Color.Green : Color.Red;
}
So the new code become
public class ComparisonBehavior : Behavior<Entry>
{
private Entry thisEntry;
static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(ComparisonBehavior), false);
public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
public static readonly BindableProperty CompareToEntryProperty = BindableProperty.Create("CompareToEntry", typeof(Entry), typeof(ComparisonBehavior), null);
public Entry CompareToEntry
{
get { return (Entry)base.GetValue(CompareToEntryProperty); }
set
{
base.SetValue(CompareToEntryProperty, value);
if (CompareToEntry != null)
CompareToEntry.TextChanged -= baseValue_changed;
value.TextChanged += baseValue_changed;
}
}
void baseValue_changed(object sender, TextChangedEventArgs e)
{
IsValid = ((Entry)sender).Text.Equals(thisEntry.Text);
thisEntry.TextColor = IsValid ? Color.Green : Color.Red;
}
public bool IsValid
{
get { return (bool)base.GetValue(IsValidProperty); }
private set { base.SetValue(IsValidPropertyKey, value); }
}
protected override void OnAttachedTo(Entry bindable)
{
thisEntry = bindable;
if (CompareToEntry != null)
CompareToEntry.TextChanged += baseValue_changed;
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
if (CompareToEntry != null)
CompareToEntry.TextChanged -= baseValue_changed;
base.OnDetachingFrom(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
string theBase = CompareToEntry.Text;
string confirmation = e.NewTextValue;
IsValid = (bool)theBase?.Equals(confirmation);
((Entry)sender).TextColor = IsValid ? Color.Green : Color.Red;
}
}
I have developed custom control to validate our model using data annotation method.
Here is project url.
https://github.com/MaulikParmar/XamarinForms/tree/master/ValidationDemo
It is not working for window 8.1 phone.
Here is youtube url for project description and how to use this control more effectively.
https://www.youtube.com/watch?v=eEi-Oky4U08
If you want to add exception handling because of System.InvalidOperationException error is showing when typing confirm password first before typing a password.
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
try
{
string theBase = CompareToEntry.Text;
string confirmation = e.NewTextValue;
IsValid = (bool)theBase?.Equals(confirmation);
((Entry)sender).TextColor = IsValid ? Color.FromHex("#e6a94d")/*correct*/ : Color.FromHex("#CD5C5C")/*incorrect*/;
}
catch (System.InvalidOperationException)
{
string theBase = CompareToEntry.Text;
string confirmation = e.NewTextValue;
((Entry)sender).TextColor = IsValid ? Color.FromHex("#e6a94d")/*correct*/ : Color.FromHex("#CD5C5C")/*incorrect*/;
}
}

How to create command menu item with checkbox?

I'm writing a VSPackage and I need to have menu item with checkbox, just like on this sample image below:
I went through this msdn reference regarding .vsct files, bud didn't fine any information explaining how to do it. What I have now is standard menu item with icon and text (code sample from MyPackage.vsct file):
<Buttons>
<Button guid="guidMyPackageCmdSet" id="cmdidMyPackage" type="Button">
<Icon guid="guidImages" id="myPackageBitmap" />
<CommandFlag>TextChanges</CommandFlag>
<CommandFlag>DontCache</CommandFlag>
<CommandFlag>FixMenuController</CommandFlag>
<Strings>
<ButtonText>MyPackage</ButtonText>
</Strings>
</Button>
</Buttons>
I need this additional checkbox. How to do it?
The properties like Checked, Visible, Enabled or Supported can´t be defined via the VSCT file. You need a command handler that controls the command´s state. I´ve created a base class that wraps the creation of the OleMenuCommand instance and handles the command´s BeforeQueryStatus event. This is a slimmed version of my implementation, but it will give you an idea how to solve it...
internal abstract class CommandHandler : IDisposable
{
private readonly OleMenuCommand command;
protected CommandHandler(Guid group, int id)
{
var commandid = CommandID(group, id);
this.command = new OleMenuCommand(this.Invoke, commandId);
this.command.BeforeQueryStatus += this.OnBeforeQueryStatus;
}
protected virtual void OnExecute() { }
protected virtual void OnQueryStatus(QueryStatusEventArgs e) { }
private void Invoke(object sender, EventArgs e)
{
this.OnExecute();
}
private void OnBeforeQueryStatus(object sender, EventArgs e)
{
OleMenuCommand command;
if ((command = sender as OleMenuCommand) != null)
{
var e = new QueryCommandEventArgs
{
Checked = command.Checked,
}
this.OnQueryStatus(e);
command.Checked = e.Checked;
}
}
public void Dispose()
{
this.command.BeforeQueryStatus -= this.OnBeforeQueryStatus;
}
}
public class QueryCommandEventArgs : EventArgs
{
public bool Checked { get; set; }
}
The CommandHandler class allows to control the state of any menu command. Just derive new handler implementations from it and override the OnExecute and OnQueryStatus methods, like...
internal sealed class MyCommand : CommandHandler
{
private bool checked;
public MyCommand() : base(GuidCmdSet, MyCommandId) { }
protected override void OnExecute()
{
this.checked = !this.checked; // toggle checked state
}
protected override void OnQueryStatus(QueryStatusEventArgs e)
{
e.Checked = this.checked;
}
}

Xamarin Forms Behavior is not attaching

I have written a very simple Xamarin Forms Behavior to set a max length for an Entry. However, it is not attaching. The OnAttach code does not execute. This is the first behavior I have written.
I have an OnAttachedTo and OnDetachedFrom.
public class MaxLengthBehavior : Behavior<Entry>
{
public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthBehavior), 0);
public int MaxLength
{
get { return (int)GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}
private void bindable_TextChanged(object sender, TextChangedEventArgs e)
{
if (e.NewTextValue.Length >= MaxLength)
((Entry)sender).Text = e.NewTextValue.Substring(0, MaxLength);
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += bindable_TextChanged;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= bindable_TextChanged;
}
}
I use Xaml to attach to an Entry.
<Entry x:Name="entryName" Margin="35, 20, 35, 9"
Placeholder="What's your name?"
Text="{Binding Name}">
<Entry.Behaviors>
<b:MaxLengthBehavior MaxLength="22" />
</Entry.Behaviors>
</Entry>
I am sure I must be doing something wrong. However, I do not see it.
Thanks.
I will post what I use and maybe it will help. This works at least for me. Main difference is that MaxLength is not BindableProperty.
public class EntryLengthValidatorBehavior : Behavior<Entry>
{
public int MaxLength { get; set; }
protected override void OnAttachedTo(Entry bindable)
{
base.OnAttachedTo(bindable);
bindable.TextChanged += OnEntryTextChanged;
}
protected override void OnDetachingFrom(Entry bindable)
{
base.OnDetachingFrom(bindable);
bindable.TextChanged -= OnEntryTextChanged;
}
void OnEntryTextChanged(object sender, TextChangedEventArgs e)
{
var entry = (Entry)sender;
// if Entry text is longer then valid length
if (entry.Text?.Length > this.MaxLength)
{
string entryText = entry.Text;
entryText = entryText.Remove(entryText.Length - 1); // remove last char
entry.Text = entryText;
}
}
}
and usage
<Entry Text="{Binding VatNumber}">
<Entry.Behaviors>
<behaviors:EntryLengthValidatorBehavior MaxLength="14" />
</Entry.Behaviors>
</Entry>
It turns out that it was a build issue with VS for Mac. I had not closed VS or the project for a couple of days. Closing and reopening VS for Mac fixed the issue. I am really starting to dislike VS for Mac. I get a lot of weirdness on solutions that are not just demo apps.

Resources