Hello,
Welcome to our Microsoft Q&A platform!
You could use TriggerAction
to achieve it.
using System.ComponentModel;
using Xamarin.Forms;
namespace ShowHidePasswordTrigger
{
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;
}
}
Then use it in the ImageVIew.
<StackLayout VerticalOptions="Center"
Padding="20">
<Grid>
<Entry Placeholder="Password"
IsPassword="{Binding Source={x:Reference ShowPasswordActualTrigger}, Path=HidePassword}"/>
<ImageButton VerticalOptions="Center"
Margin="0,0,10,0"
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>
</Grid>
</StackLayout>
In your layout, you can add following code,
<StackLayout Padding="3" Orientation="Horizontal">
<!--<local:CustomEntry
x:Name="password_entry"
IsPassword="True"
Text="abcdef"
Placeholder="Password"
Style="{StaticResource LoginEntryStyle}"/>
<Image
x:Name="password_icon"
Style="{StaticResource LoginEntryImageStyle}"
HorizontalOptions="End"
Source="ic_hide_password_xx.png">
<Image.GestureRecognizers>
<TapGestureRecognizer
Tapped="PasswordIcon_Clicked"
NumberOfTapsRequired="1">
</TapGestureRecognizer>
</Image.GestureRecognizers>
</Image>-->
<Entry Placeholder="Password"
Grid.Column="0"
IsPassword="{Binding Source={x:Reference ShowPasswordActualTrigger}, Path=HidePassword}"/>
<ImageButton
Grid.Column="1"
BackgroundColor="Transparent"
Margin="0,0,10,0"
HeightRequest="20"
HorizontalOptions="End"
Source="ic_eye_hide">
<ImageButton.Triggers>
<EventTrigger Event="Clicked">
<local1:ShowPasswordTriggerAction ShowIcon="ic_eye"
HideIcon="ic_eye_hide"
x:Name="ShowPasswordActualTrigger"/>
</EventTrigger>
</ImageButton.Triggers>
</ImageButton>
</StackLayout>
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.