密碼方塊Password box

密碼方塊是一個文字輸入方塊,會基於隱私權考量而隱藏輸入其中的字元。A password box is a text input box that conceals the characters typed into it for the purpose of privacy. 密碼方塊看起來就像文字方塊,只不過它會將已輸入的文字轉譯成預留位置字元。A password box looks like a text box, except that it renders placeholder characters in place of the text that has been entered. 您可以設定預留位置字元。You can configure the placeholder character.

根據預設,密碼方塊會提供一種方式,讓使用者能夠藉由按住顯示按鈕來檢視他們的密碼。By default, the password box provides a way for the user to view their password by holding down a reveal button. 您可以停用顯示按鈕,或提供替代機制來顯示密碼,例如核取方塊。You can disable the reveal button, or provide an alternate mechanism to reveal the password, such as a check box.

取得 Windows UI 程式庫Get the Windows UI Library

WinUI 標誌

Windows UI 程式庫 2.2 或更新版本中有這個控制項使用圓角的新範本。Windows UI Library 2.2 or later includes a new template for this control that uses rounded corners. 如需詳細資訊,請參閱圓角半徑For more info, see Corner radius. WinUI 是 NuGet 套件,其中包含適用於 Windows 應用程式的新控制項和 UI 功能。WinUI is a NuGet package that contains new controls and UI features for Windows apps. 如需詳細資訊 (包括安裝指示),請參閱 Windows UI 程式庫For more info, including installation instructions, see Windows UI Library.

平台 APIPasswordBox 類別Password 屬性PasswordChar 屬性PasswordRevealMode 屬性PasswordChanged 事件Platform APIs: PasswordBox class, Password property, PasswordChar property, PasswordRevealMode property, PasswordChanged event

這是正確的控制項嗎?Is this the right control?

使用 PasswordBox 控制項,以收集密碼或其他私人資料,例如身分證字號。Use a PasswordBox control to collect a password or other private data, such as a Social Security number.

如需如何選擇正確文字控制項的詳細資訊,請參閱文字控制項文章。For more info about choosing the right text control, see the Text controls article.

範例Examples

XAML 控制項庫XAML Controls Gallery
XAML controls gallery

如果您已安裝 XAML 控制項庫應用程式,請按一下這裡開啟應用程式並查看 PasswordBox 運作情形If you have the XAML Controls Gallery app installed, click here to open the app and see the PasswordBox in action.

密碼方塊有數個狀態,包括這些值得注意的狀態。The password box has several states, including these notable ones.

靜止的密碼方塊可以顯示提示文字,讓使用者知道其用途:A password box at rest can show hint text so that the user knows its purpose:

處於靜止狀態的密碼方塊與提示文字

當使用者在密碼方塊中輸入時,預設行為是顯示將輸入文字隱藏的項目符號:When the user types in a password box, the default behavior is to show bullets that hide the text being entered:

密碼方塊焦點狀態輸入文字

按右邊的 [顯示] 按鈕可窺看正輸入的密碼文字:Pressing the "reveal" button on the right gives a peek at the password text being entered:

密碼方塊文字已顯示

建立密碼方塊Create a password box

使用 Password 屬性來取得或設定 PasswordBox 的內容。Use the Password property to get or set the contents of the PasswordBox. 您可以在處理常式中針對 PasswordChanged 事件執行此動作,在使用者輸入密碼時執行驗證。You can do this in the handler for the PasswordChanged event to perform validation while the user enters the password. 您可以使用另一個事件 (例如按鈕 Click),在使用者完成文字輸入之後執行驗證。Or, you can use another event, like a button Click, to perform validation after the user completes the text entry.

以下是適用於密碼方塊控制項的 XAML,該控制項展示 PasswordBox 的預設外觀。Here's the XAML for a password box control that demonstrates the default look of the PasswordBox. 當使用者輸入密碼時,您會檢查該控制項以確認是否為「Password」常值。When the user enters a password, you check to see if it's the literal value, "Password". 如果是,您會向使用者顯示訊息。If it is, you display a message to the user.

<StackPanel>  
  <PasswordBox x:Name="passwordBox" Width="200" MaxLength="16"
             PasswordChanged="passwordBox_PasswordChanged"/>

  <TextBlock x:Name="statusText" Margin="10" HorizontalAlignment="Center" />
</StackPanel>   
private void passwordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
    if (passwordBox.Password == "Password")
    {
        statusText.Text = "'Password' is not allowed as a password.";
    }
    else
    {
        statusText.Text = string.Empty;
    }
}

以下是執行此程式碼且使用者輸入「Password」時的結果。Here's the result when this code runs and the user enters "Password".

含驗證訊息的密碼方塊

密碼字元Password character

您可以設定 PasswordChar 屬性,來變更用來設定密碼遮罩的字元。You can change the character used to mask the password by setting the PasswordChar property. 這裡會使用星號來取代預設的項目符號。Here, the default bullet is replaced with an asterisk.

<PasswordBox x:Name="passwordBox" Width="200" PasswordChar="*"/>

結果看起來就像這樣。The result looks like this.

含自訂字元的密碼方塊

標頭與預留位置文字Headers and placeholder text

您可以使用 HeaderPlaceholderText 屬性來提供 PasswordBox 的內容。You can use the Header and PlaceholderText properties to provide context for the PasswordBox. 當您有多個方塊時 (例如,在表單上變更密碼),這特別有用。This is especially useful when you have multiple boxes, such as on a form to change a password.

<PasswordBox x:Name="passwordBox" Width="200" Header="Password" PlaceholderText="Enter your password"/>

處於靜止狀態的密碼方塊與提示文字

長度上限Maximum length

藉由設定 MaxLength 屬性,來指定使用者可以輸入的字元數目上限。Specify the maximum number of characters that the user can enter by setting the MaxLength property. 沒有任何屬性可用來指定最小長度,但您可以在 app 程式碼中檢查密碼長度並執行任何其他驗證。There is no property to specify a minimum length, but you can check the password length, and perform any other validation, in your app code.

密碼顯示模式Password reveal mode

PasswordBox 有一個內建按鈕,使用者按下該按鈕就會顯示密碼文字。The PasswordBox has a built-in button that the user can press to display the password text. 以下是使用者動作的結果。Here's the result of the user's action. 當使用者放開按鈕後,密碼就會自動再次隱藏。When the user releases it, the password is automatically hidden again.

密碼方塊文字已顯示

預覽模式Peek mode

預設會顯示密碼顯示按鈕 (或「預覽」按鈕)。By default, the password reveal button (or "peek" button) is shown. 使用者必須持續按住該按鈕才能檢視密碼,如此便能維持高等級的安全性。The user must continuously press the button to view the password, so that a high level of security is maintained.

PasswordRevealMode 屬性的值並非決定是否要讓使用者看見密碼顯示按鈕的唯一因素。The value of the PasswordRevealMode property is not the only factor that determines whether a password reveal button is visible to the user. 其他因素包括控制項是否會以大於最小寬度的形式來顯示、PasswordBox 是否具有焦點,以及文字輸入欄位是否包含至少一個字元。Other factors include whether the control is displayed above a minimum width, whether the PasswordBox has focus, and whether the text entry field contains at least one character. 密碼顯示按鈕只有在 PasswordBox 第一次收到焦點且輸入字元時才會顯示。The password reveal button is shown only when the PasswordBox receives focus for the first time and a character is entered. 如果 PasswordBox 失去焦點,然後重新取得焦點,除非將密碼清除並重新開始輸入字元,否則顯示按鈕將不會再次顯示。If the PasswordBox loses focus and then regains focus, the reveal button is not shown again unless the password is cleared and character entry starts over.

注意  在 Windows 10 之前,預設不會顯示密碼顯示按鈕。Caution  Prior to Windows 10, the password reveal button was not shown by default. 如果您 app 的安全性需要一律隱藏密碼,請務必將 PasswordRevealMode 設為 Hidden。If the security of your app requires that the password is always obscured, be sure to set PasswordRevealMode to Hidden.

隱藏和顯示模式Hidden and Visible modes

其他的 PasswordRevealMode 列舉值 (HiddenVisible) 會隱藏密碼顯示按鈕,並讓您能夠以程式設計的方式來管理是否要隱藏密碼。The other PasswordRevealMode enumeration values, Hidden and Visible, hide the password reveal button and let you programmatically manage whether the password is obscured.

若要一律隱藏密碼,請將 PasswordRevealMode 設定為 Hidden。To always obscure the password, set PasswordRevealMode to Hidden. 除非您需要一律隱藏密碼,否則,您可以提供自訂的 UI,讓使用者能夠在 Hidden 和 Visible 之間切換 PasswordRevealMode。Unless you need the password to be always obscured, you can provide a custom UI to let the user toggle the PasswordRevealMode between Hidden and Visible. 例如,您可以使用核取方塊來切換是否遮蔽密碼,如下列範例所示。For example, you can use a check box to toggle whether the password is obscured, as shown in the following example. 您也可以使用其他控制項 (例如 ToggleButton),讓使用者能夠切換模式。You can also use other controls, like ToggleButton, to let the user switch modes.

這個範例示範如何使用 CheckBox,讓使用者能夠切換 PasswordBox 的顯示模式。This example shows how to use a CheckBox to let a user switch the reveal mode of a PasswordBox.

<StackPanel Width="200">
    <PasswordBox Name="passwordBox1"
                 PasswordRevealMode="Hidden"/>
    <CheckBox Name="revealModeCheckBox" Content="Show password"
              IsChecked="False"
              Checked="CheckBox_Changed" Unchecked="CheckBox_Changed"/>
</StackPanel>
private void CheckBox_Changed(object sender, RoutedEventArgs e)
{
    if (revealModeCheckBox.IsChecked == true)
    {
        passwordBox1.PasswordRevealMode = PasswordRevealMode.Visible;
    }
    else
    {
        passwordBox1.PasswordRevealMode = PasswordRevealMode.Hidden;
    }
}

這個 PasswordBox 看起來就像這樣。This PasswordBox looks like this.

含自訂顯示按鈕的密碼方塊

選擇文字控制項的正確鍵盤Choose the right keyboard for your text control

為協助使用者使用觸控式鍵盤或螢幕輸入面板 (SIP) 輸入資料,您可以設定文字控制項的輸入範圍,使其符合使用者要輸入的資料類型。To help users to enter data using the touch keyboard, or Soft Input Panel (SIP), you can set the input scope of the text control to match the kind of data the user is expected to enter. PasswordBox 只支援 PasswordNumericPin 輸入範圍值。PasswordBox supports only the Password and NumericPin input scope values. 會略過其他任何值。Any other value is ignored.

如需如何使用輸入範圍的詳細資訊,請參閱使用輸入範圍來變更觸控式鍵盤For more info about how to use input scopes, see Use input scope to change the touch keyboard.

建議Recommendations

  • 如果密碼方塊的用途不清楚,請使用標籤或預留位置文字。Use a label or placeholder text if the purpose of the password box isn't clear. 無論文字輸入方塊是否包含值,都會顯示標籤。A label is visible whether or not the text input box has a value. 預留位置文字會顯示在文字輸入方塊內,只要輸入值就會消失。Placeholder text is displayed inside the text input box and disappears once a value has been entered.
  • 為密碼方塊指定一個適合可輸入的值範圍的寬度。Give the password box an appropriate width for the range of values that can be entered. 每個語言的單字長度都不相同,所以如果您希望您的應用程式能夠全球化,請考慮到當地語系化。Word length varies between languages, so take localization into account if you want your app to be world-ready.
  • 不要在密碼輸入方塊旁邊放置另一個控制項。Don't put another control right next to a password input box. 密碼方塊有一個顯示密碼按鈕,可以讓使用者驗證所輸入的密碼,而在旁邊放置一個控制項,使用者可能會在嘗試與另一個控制項互動時,不小心顯示密碼。The password box has a password reveal button for users to verify the passwords they have typed, and having another control right next to it might make users accidentally reveal their passwords when they try to interact with the other control. 為了避免這種情況發生,請在密碼輸入方塊與另一個控制項之間保留一些間距,或是將另一個控制項放到下一行。To prevent this from happening, put some spacing between the password in put box and the other control, or put the other control on the next line.
  • 考慮呈現兩個建立帳戶的密碼方塊:一個用於新密碼,第二個用來確認新密碼。Consider presenting two password boxes for account creation: one for the new password, and a second to confirm the new password.
  • 只顯示一個用於登入的單一密碼方塊。Only show a single password box for logins.
  • 當密碼方塊是用來輸入 PIN 時,請考慮在輸入最後一個數字時便提供立即回應,而不是使用確認按鈕。When a password box is used to enter a PIN, consider providing an instant response as soon as the last number is entered instead of using a confirmation button.

取得範例程式碼Get the sample code

文字控制項Text controls