如何修改密码盒的MaxLength ?



我试图能够根据另一个控件更改密码框的MaxLength。当用户单击toggleButton时,如何更改passwordBox的MaxLength

下面是我为toggleBox和PasswordBox的代码,但这只允许1作为maxLength时切换。

<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"/>

你可以这样做:

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

和使用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();
}
}

您可以使用StyleDataTrigger来设置MaxLength属性:

<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>

相关内容

  • 没有找到相关文章

最新更新