3

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 ?

Raj
  • 837
  • 4
  • 15
  • 24

4 Answers4

5

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

Sgr3005
  • 94
  • 1
  • 4
3

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;
}
Daniel
  • 10,864
  • 22
  • 84
  • 115
  • 2
    that doesn't prevent the 'paste' – NSGaga-mostly-inactive Apr 12 '13 at 13:12
  • @NSGaga was looking for help on read only password box myself. I suppose to handle the paste issues you could add a PreviewKeyDown event that also sets `e.Handled = true;` then disable the PasswordBox ContextMenu in XAML with `ContextMenu="{x:Null}` – famousKaneis Jul 11 '14 at 15:06
  • 1
    @codeSwearing I was just nitpicking :). Seriously, you may be right, but I don't think that's the best way, as it leads many roads open, keyboard, mouse & other input events etc. As I'm looking at this, I'm not sure why the OP needs this in the first place, but hey, I'd rather change the style of the 'disabled' password box to look like enabled, handle triggers etc. Or do the get with no 'set' as suggested (via attached properties) or something similar. – NSGaga-mostly-inactive Jul 11 '14 at 18:08
2

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" />
Community
  • 1
  • 1
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
0

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

Murphybro2
  • 2,207
  • 1
  • 22
  • 36