Raj
Raj

Reputation: 837

How to make password box non-editable in wpf

I need to make password box as non-editable in wpf. I used
IsEnabled = false

But it is affecting my style some blur effect came because of that... Is there any other way to achieve this ?

Upvotes: 3

Views: 4342

Answers (4)

Sgr3005
Sgr3005

Reputation: 94

I know this is two years old, but I had the same need and solved it this way: The combination of these two properties, both set to false, will prevent entry/editing in the control, w/o affecting your desired style: Focusable, IsHitTestVisible

Upvotes: 5

Murphybro2
Murphybro2

Reputation: 2689

Pretty simple..

Set an event handler for PreviewTextInput in your XML like so:

    PreviewTextInput="PasswordBoxOnPreviewTextInput"

And within that method:

    private void PasswordBoxOnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        if (m_DisablePasswordBox)
            e.Handled = true;
    }

It will now prevent you from typing anything in :)

Upvotes: 0

NSGaga
NSGaga

Reputation: 14302

One solution is to make a custom functionality to mimic the IsReadOnly.

There are couple things to take care of - e.g. clipboard pasting also.

You'll get similar behavior by defining some attached property (e.g. IsPasswordReadOnly or just the same) - which would work out all that's required.

Here is a good starting example - which could, should I think work for Password box as well - but I haven't tried it and you gotta test yourself.

Readonly textbox for WPF with visible cursor (.NET 3.5)

You'd have to replace references to TextBox with PasswordBox, rename it to IsReadOnly - and I think the rest might work the same.

And you use it like...

<PasswordBox my:AttachReadOnly.IsReadOnly="True" />

Upvotes: 2

Daniel
Daniel

Reputation: 11054

You can handle the PreviewTextInput event, preventing the user from entering text. Like so:

Xaml:

<PasswordBox PreviewTextInput="HandleInput"/>

Codebehind:

private void HandleInput(object sender, TextCompositionEventArgs e) {
  e.Handled = true;
}

Upvotes: 3

Related Questions