[英]System.InvalidOperationException on Button.Content in WPF
[英]How to set MaxLength in PasswordBox when input is Button.Content instead of keyboard? (WPF)
我有一個帶有0-9的簡單鍵盤,一個清除按鈕和一個輸入按鈕。 單擊數字將內容放入PasswordBox。 單擊“清除”按鈕將模擬退格,並且“輸入”按鈕充當預定義4位數字代碼的提交。 如果輸入正確的代碼,它將附加到一個文本框,顯示已授予訪問權限,否則,訪問被拒絕。
除了嘗試在PasswordBox上設置MaxLength之外,我沒有任何問題。 我已經在XAML中使用以下方法進行了嘗試:
<PasswordBox PasswordChanged="securityCodeTextBox_PasswordChanged" MaxLength="4" KeyDown="securityCodeTextBox_KeyDown" x:Name="securityCodeTextBox" PasswordChar="•" HorizontalAlignment="Left" Margin="117,20,0,0" VerticalAlignment="Top" Height="23" Width="213"/>
我還通過以下方式通過程序進行了嘗試:
securityCodeTextBox.MaxLength = 4;
這是我的函數中數字按鈕的唯一代碼:
private void ButtonClickNum(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
securityCodeTextBox.Password += button.Content.ToString();
}
我不必執行此操作,因為如果代碼錯誤,它將僅在其下面的文本框中記錄“訪問被拒絕”。 但是,我對實現MaxLength是用於鍵盤輸入而不是按鈕單擊之后的操作感到非常好奇。 我目前使用以下命令完全禁用了鍵盤:
//Prevent keyboard input
private void securityCodeTextBox_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
下次嘗試
我創建了一個非常草率的方法,如果長度達到> = 4,則禁用除“清除”和“輸入”按鈕之外的所有按鈕,並在Num和“清除按鈕的單擊”功能中使用以下代碼段:
private void ButtonClickNum(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
securityCodeTextBox.Password += button.Content.ToString();
//Disable all buttons if MaxLength is reached
if(securityCodeTextBox.Password.Length >= 4)
{
button0.IsEnabled = false;
button1.IsEnabled = false;
button2.IsEnabled = false;
button3.IsEnabled = false;
button4.IsEnabled = false;
button5.IsEnabled = false;
button6.IsEnabled = false;
button7.IsEnabled = false;
button8.IsEnabled = false;
button9.IsEnabled = false;
}
}
清除按鈕
/**
* Remove(int startIndex, int count) startIndex = position, count = num of chars to delete
*/
private void ButtonClickClear(object sender, RoutedEventArgs e)
{
if (securityCodeTextBox.Password.Length > 0)
{
securityCodeTextBox.Password = securityCodeTextBox.Password.Remove(securityCodeTextBox.Password.Length - 1, 1);
}
//Enable all the buttons again once password is less than MaxLength
if (securityCodeTextBox.Password.Length < 4)
{
button0.IsEnabled = true;
button1.IsEnabled = true;
button2.IsEnabled = true;
button3.IsEnabled = true;
button4.IsEnabled = true;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
button9.IsEnabled = true;
}
}
當輸入是按鈕的內容時,是否存在一種更干凈的方法來實現MaxLength方法?
我以前從未使用過WPF或密碼輸入控件,但我會這樣嘗試,如果達到長度,它將不會添加密碼。
private void ButtonClickNum(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
if(securityCodeTextBox.Password.Length < 4)
securityCodeTextBox.Password += button.Content.ToString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.