WPF passwordbox如何禁止复制粘贴,不使用自定义控件的情况下
时间: 2024-04-15 09:28:37
浏览: 134
如果你不想使用自定义控件,你仍然可以在WPF中禁止PasswordBox控件的复制和粘贴操作。以下是一种方法:
1. 使用Attached Property(附加属性)来控制PasswordBox的行为。
```csharp
public static class PasswordBoxHelper
public static readonly DependencyProperty IsCopyPasteEnabledProperty =
DependencyProperty.RegisterAttached("IsCopyPasteEnabled", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(true, OnIsCopyPasteEnabledC[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)ged));
public static bool GetIsCopyPasteEnabled(DependencyObject obj)
return (bool)obj.GetValue(IsCopyPasteEnabledProperty);
public static void SetIsCopyPasteEnabled(DependencyObject obj, bool value)
obj.SetValue(IsCopyPasteEnabledProperty, value);
private static void OnIsCopyPasteEnabledC[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)ged(DependencyObject d, DependencyPropertyC[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)gedEventArgs e)
if (d is PasswordBox passwordBox)
if ((bool)e.NewValue)
passwordBox.PreviewKeyDown += PasswordBox_PreviewKeyDown;
DataObject.AddPasting[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)dler(passwordBox, PasswordBox_Pasting);
passwordBox.PreviewKeyDown -= PasswordBox_PreviewKeyDown;
DataObject.RemovePasting[han](https://geek.csdn.net/educolumn/0d22b54eaf6bcf967d9625e1679d00b4?spm=1055.2569.3001.10083)dler(passwordBox, PasswordBox_Pasting);
private static void PasswordBox_PreviewKeyDown(object sender, KeyEventArgs e)
if ((e.Key == Key.V || e.Key == Key.C || e.Key == Key.X) && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
e.Handled = true;
private static void PasswordBox_Pasting(object sender, DataObjectPastingEventArgs e)
e.CancelCommand();
```
相关推荐














