Home > Software design >  How do I change the MaxLength of the PasswordBox
How do I change the MaxLength of the PasswordBox

Time:07-05

I am trying to be able to change the MaxLength of the Password box based on another control. how do I change the passwordBox MaxLength when user clicks the toggleButton.

Below is the code I have for the toggleBox and PasswordBox but this is only allowing 1 as the maxLength when toggled.

<PasswordBox MaxLength="{Binding ElementName=toggleUseToken, Path=IsChecked, Mode=OneWay}" x:Name="textboxPassword" BorderThickness="0" ToolTip="Enter your password" Password="password" Style="{StaticResource textboxpassword}" Grid.Column="1"/>

<ToggleButton x:Name="toggleUseToken" Grid.Column="3" ToolTip="Remember Me" Style="{StaticResource toggleToken}" Height="20"/>

CodePudding user response:

You can do something like this:

<StackPanel>
    <PasswordBox MaxLength="{Binding ElementName=ToggleButton, Path=IsChecked, Converter={StaticResource ToggleButtonToMaxLengthConverterKey}}"/>
    <ToggleButton x:Name="ToggleButton" Content="Set Length"/>
</StackPanel>

And use Converter:

public class ToggleButtonToMaxLengthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool isChecked)
        {
            return isChecked ? 5 : 12;
        }

        return 12;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

CodePudding user response:

You could a Style with a DataTrigger to set the MaxLength property:

<PasswordBox x:Name="textboxPassword" BorderThickness="0" ToolTip="Enter your password" Password="password" Grid.Column="1">
    <PasswordBox.Style>
        <Style TargetType="PasswordBox" BasedOn="{StaticResource textboxpassword}">
            <Setter Property="MaxLength" Value="12" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, ElementName=toggleUseToken}" Value="True">
                    <Setter Property="MaxLength" Value="5" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </PasswordBox.Style>
</PasswordBox>
  • Related