Best approach for show/hide password toggle functionality in Xamarin traditional approach

We are working on show/ hide password toggle functionality in Xamarin traditional approach. What is the best place to implement it? Is it in Xamarin.iOS &. Droid or in Xamarin.Core?

If it is in Xamarin.Core, can you let us know the process. Is it by value convertors?

Thanks in advance.

Upvotes: 4

Views: 6883

Answers (5)

rob_james
rob_james

Reputation: 1322

Trigger and a command

The trigger changes the icon, and the command changes the entry.

View xaml

<Grid>
      <Entry Placeholder="Password" Text="{Binding Password, Mode=TwoWay}" IsPassword="{Binding IsPassword}" />
      <ImageButton BackgroundColor="Transparent" WidthRequest="24" VerticalOptions="Center" TranslationY="-5" TranslationX="-10" HorizontalOptions="End"
          Command="{Binding ToggleIsPassword}"
          Source="eye"   >
          <ImageButton.Triggers>
              <DataTrigger TargetType="ImageButton" Binding="{Binding IsPassword}" Value="True" >
                  <Setter Property="Source" Value="eye-slash" />
              </DataTrigger>
          </ImageButton.Triggers>
      </ImageButton>
    </Grid>

And in my ViewModel

private bool _IsPassword = true;
public bool IsPassword
{
    get
    {
        return _IsPassword;
    }
    set
    {
        _IsPassword = value;
        RaisePropertyChanged(() => IsPassword);
    }
}
public ICommand ToggleIsPassword => new Command(() => IsPassword = !IsPassword);

Upvotes: 0

pseudoankit
pseudoankit

Reputation: 329

Your UI codes like this having a entry and image button source to named accroding to your ui

<Frame CornerRadius="30" Background="white" Padding="0" HeightRequest="43" Margin="0,17,0,0">
                <StackLayout Orientation="Horizontal">
                    <Entry x:Name="eLoginPassword"                        
                            Margin="15,-10,0,-15"
                            HorizontalOptions="FillAndExpand"                            
                            IsPassword="True"
                            Placeholder="Password"/>
                    <ImageButton
                            x:Name="ibToggleLoginPass"
                            Clicked="IbToggleLoginPass"
                            Source="eyeclosed"
                            Margin="0,0,13,0"
                            BackgroundColor="White"
                            HorizontalOptions="End"
                            />
                </StackLayout>
            </Frame>

in C# code

 // IbToggleLoginPass your defined method in xaml
    //"eye" is drawable name for open eye and "eyeclosed" is drawable name for closed eye
    private void IbToggleLoginPass(object sender, EventArgs e)
            {
                bool isPass = eLoginPassword.IsPassword;
                ibToggleLoginPa`enter code here`ss.Source = isPass ? "eye" : "eyeclosed";
                eLoginPassword.IsPassword = !isPass;
            }

Upvotes: 1

Saamer
Saamer

Reputation: 5119

Recently, Microsoft MVP Charlin, wrote an article showing how to do this using Event Triggers in the Xamarin Forms code:

GIF Showing Show and Hide Functionality

She was able to do it simply using a new ShowPasswordTriggerAction of type TriggerAction that implemented INotifyPropertyChanged. Therein, she created a HidePassword bool property that Invoke a PropertyChanged event which changes the Source of the Icon image:

protected override void Invoke(ImageButton sender)
{
    sender.Source = HidePassword ? ShowIcon : HideIcon;
    HidePassword = !HidePassword;
}

Then place the Entry and ImageButton inside a layout (like a Frame or horizontally oriented LinearLayout) as shown:

  <Entry Placeholder="Password"
         IsPassword="{Binding Source={x:Reference ShowPasswordActualTrigger}, Path=HidePassword}"/>
  <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>

Upvotes: 5

stackunderflows
stackunderflows

Reputation: 170

You can use the PhantomLib library to do this. It has a control which allows you to have a show/hide icon for the password with examples. Just install the nuget. https://github.com/OSTUSA/PhantomLib

Upvotes: 1

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10978

We always use custom controls to show/hide password while entering the password using effects.

Android:

Create the control manually in ‘OnDrawableTouchListener’ method where, we are adding the ShowPass and HidePass icons to the entry control, changing them on the basis of user touch action and attaching it on effect invocation which will be fired when the effect is added to the control.

public class OnDrawableTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener  
{  
    public bool OnTouch(Android.Views.View v, MotionEvent e)  
    {  
        if (v is EditText && e.Action == MotionEventActions.Up)  
        {  
            EditText editText = (EditText)v;  
            if (e.RawX >= (editText.Right - editText.GetCompoundDrawables()[2].Bounds.Width()))  
            {  
                if (editText.TransformationMethod == null)  
                {  
                    editText.TransformationMethod = PasswordTransformationMethod.Instance;  
                    editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, Resource.Drawable.ShowPass, 0);  
                }  
                else  
                {  
                    editText.TransformationMethod = null;  
                    editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, Resource.Drawable.HidePass, 0);  
                }  

                return true;  
            }  
        }  

        return false;  
    }  
}  

Result:

enter image description here

IOS:

Create the control manually in 'ConfigureControl' method where we are adding the ShowPass and HidePassicons to the entry control, changing them on the basis of user touch action; and attaching it on effect invocation which will be fired when the effect will be added to the control.

private void ConfigureControl()  
    {  
        if (Control != null)  
        {  
            UITextField vUpdatedEntry = (UITextField)Control;  
            var buttonRect = UIButton.FromType(UIButtonType.Custom);  
            buttonRect.SetImage(new UIImage("ShowPass"), UIControlState.Normal);  
            buttonRect.TouchUpInside += (object sender, EventArgs e1) =>  
            {  
                if (vUpdatedEntry.SecureTextEntry)  
                {  
                    vUpdatedEntry.SecureTextEntry = false;  
                    buttonRect.SetImage(new UIImage("HidePass"), UIControlState.Normal);  
                }  
                else  
                {  
                    vUpdatedEntry.SecureTextEntry = true;  
                    buttonRect.SetImage(new UIImage("ShowPass"), UIControlState.Normal);  
                }  
            };  

            vUpdatedEntry.ShouldChangeCharacters += (textField, range, replacementString) =>  
            {  
                string text = vUpdatedEntry.Text;  
                var result = text.Substring(0, (int)range.Location) + replacementString + text.Substring((int)range.Location + (int)range.Length);  
                vUpdatedEntry.Text = result;  
                return false;  
            };  


            buttonRect.Frame = new CoreGraphics.CGRect(10.0f, 0.0f, 15.0f, 15.0f);  
            buttonRect.ContentMode = UIViewContentMode.Right;  

            UIView paddingViewRight = new UIView(new System.Drawing.RectangleF(5.0f, -5.0f, 30.0f, 18.0f));  
            paddingViewRight.Add(buttonRect);  
            paddingViewRight.ContentMode = UIViewContentMode.BottomRight;  


            vUpdatedEntry.LeftView = paddingViewRight;  
            vUpdatedEntry.LeftViewMode = UITextFieldViewMode.Always;  

            Control.Layer.CornerRadius = 4;  
            Control.Layer.BorderColor = new CoreGraphics.CGColor(255, 255, 255);  
            Control.Layer.MasksToBounds = true;  
            vUpdatedEntry.TextAlignment = UITextAlignment.Left;  
        }  

    }  

Result:

enter image description here

For more details, please refer to the article below. https://www.c-sharpcorner.com/article/xamarin-forms-tip-implement-show-hide-password-using-effects/

You could download the source file from GitHub for reference. https://github.com/techierathore/ShowHidePassEx.git

Upvotes: 2

Related Questions