A common requirement in mobile applications is the ability to show/hide a password field. Googling I discovered that there are many ways to do it, some people create a custom control, others prefer to use a custom renderer, effects, etc.
What’s Event Trigger
An EventTrigger is a kind of Trigger that activates when the associated event of the control occurs. For example, if we want to change a property when a button is clicked (Using the event Clicked) or when the text change (Using the event TextChanged).
How it works
You have to create a new TriggerAction<ViewType> class and in the Invoke method put the code you want to be executed when the EventName specified in XAML occurs.
public class MyTriggerAction : TriggerAction<T>
{
protected override void Invoke(T sender)
{
//Code to execute
}
}Let’s create the Show/Hide password trigger
Create a TriggerAction for an ImageButton and when the user clicks on that button I will change the Source of the image button and use the Icon in the ShowIcon/HideIcon properties.
public class ShowPasswordTriggerAction : TriggerAction<ImageButton>, INotifyPropertyChanged
{
public string ShowIcon { get; set; }
public string HideIcon { get; set; }
bool _hidePassword = true;
public bool HidePassword
{
set
{
if (_hidePassword != value)
{
_hidePassword = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HidePassword)));
}
}
get => _hidePassword;
}
protected override void Invoke(ImageButton sender)
{
sender.Source = HidePassword ? ShowIcon : HideIcon;
HidePassword = !HidePassword;
}
public event PropertyChangedEventHandler PropertyChanged;
}Let’s use it
In the XAML will add the EventTrigger to an ImageButton and set the ShowIcon/HideIcon property, also will set an x:Name, which will be used later in the Entry.
<ImageButton VerticalOptions="Center" HeightRequest="20" HorizontalOptions="End" Source="ic_eye_hide"> <ImageButton.Triggers> <EventTrigger Event="Clicked"> <local:ShowPasswordTriggerAction ShowIcon="ic_eye" HideIcon="ic_eye_hide" x:Name="ShowPasswordActualTrigger"/> </EventTrigger> </ImageButton.Triggers> </ImageButton>I’ll bind the IsPassword property of the Entry to the Trigger, to hide/show the password.
<Entry Placeholder="Password"
IsPassword="{Binding Source={x:Reference ShowPasswordActualTrigger}, Path=HidePassword}"/>Demo Link

Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site. For more info:- Xamarin App Development
ReplyDelete