WPF 中PasswordBox控件的Password属性不能Binding问题解决方法

最近用到了PasswordBox控件,但是发现Password属性不能Binding,因为它不是依赖属性,在网上找了找解决方法,自己做了小Demo,方便以后使用。


一、前台文件内容

<Window x:Class="PasswordBoxDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="142" Width="256"
        xmlns:Helper="clr-namespace:PasswordBoxDemo"
        WindowStartupLocation="CenterScreen">
    <Grid>
        <ListView x:Name="lvUsers"
                  HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch"
                  >
            <ListView.View >
                <GridView x:Name="GridView">
                    <GridView.Columns>
                        <GridViewColumn Header="用户名" >
                            <GridViewColumn.CellTemplate>
                                <DataTemplate  >
                                    <TextBox 
                                             HorizontalAlignment="Stretch"
                                             VerticalAlignment="Stretch"
                                             Text="{Binding Path=UserName}"
                                             ToolTip="{Binding Path=UserName}"
                                             Width="100"
                                             Height="20"></TextBox>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn Header="密码" >
                            <GridViewColumn.CellTemplate>
                                <DataTemplate  >
                                    <PasswordBox 
                                                 HorizontalAlignment="Stretch"
                                                 VerticalAlignment="Stretch"
                                                 Width="100"
                                                 Height="20"
                                                 PasswordChar="*"
                                                 MaxLength="20"
                                                 Helper:PasswordBoxHelper.Attach="True"
                                                 Helper:PasswordBoxHelper.Password="{Binding Path=Pwd,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
/>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView.Columns>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>


二、后台内容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;


namespace PasswordBoxDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }


        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ObservableCollection<User> users = new ObservableCollection<User>();

            User p = new User();
            p.UserName = "张三";
            p.Pwd = "zhangsan";

            User p2 = new User();
            p2.UserName = "李四";
            p2.Pwd = "lisi";

            users.Add(p);
            users.Add(p2);

            this.lvUsers.ItemsSource = users;
           
        }
    }


    public class User
    {
        private string _userName;
        private string _password;
        public string UserName
        {
            set { _userName = value; }
            get { return _userName; }
        }


        public string Pwd
        {
            set { _password = value; }
            get { return _password; }
        }
    }
}


三、帮助类 PasswordBoxHelper.cs 内容,代码摘自:http://www.wpftutorial.net/PasswordBox.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;


namespace PasswordBoxDemo
{
    /// <summary>  
    /// 为PasswordBox控件的Password增加绑定功能  
    /// </summary>  
    public static class PasswordBoxHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordBoxHelper),
            new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach",
            typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false, Attach));
        private static readonly DependencyProperty IsUpdatingProperty =
           DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
           typeof(PasswordBoxHelper));


        public static void SetAttach(DependencyObject dp, bool value)
        {
            dp.SetValue(AttachProperty, value);
        }
        public static bool GetAttach(DependencyObject dp)
        {
            return (bool)dp.GetValue(AttachProperty);
        }
        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }
        public static void SetPassword(DependencyObject dp, string value)
        {
            dp.SetValue(PasswordProperty, value);
        }
        private static bool GetIsUpdating(DependencyObject dp)
        {
            return (bool)dp.GetValue(IsUpdatingProperty);
        }
        private static void SetIsUpdating(DependencyObject dp, bool value)
        {
            dp.SetValue(IsUpdatingProperty, value);
        }
        private static void OnPasswordPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            passwordBox.PasswordChanged -= PasswordChanged;
            if (!(bool)GetIsUpdating(passwordBox))
            {
                passwordBox.Password = (string)e.NewValue;
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }
        private static void Attach(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            if (passwordBox == null)
                return;
            if ((bool)e.OldValue)
            {
                passwordBox.PasswordChanged -= PasswordChanged;
            }
            if ((bool)e.NewValue)
            {
                passwordBox.PasswordChanged += PasswordChanged;
            }
        }
        private static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            SetIsUpdating(passwordBox, true);
            SetPassword(passwordBox, passwordBox.Password);
            SetIsUpdating(passwordBox, false);
        }
    }
}


四、截图



五、参考博客地址:http://blog.csdn.net/fxhflower/article/details/6614831



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果你不想使用自定义控件,你仍然可以在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, OnIsCopyPasteEnabledChanged)); 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 OnIsCopyPasteEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is PasswordBox passwordBox) { if ((bool)e.NewValue) { passwordBox.PreviewKeyDown += PasswordBox_PreviewKeyDown; DataObject.AddPastingHandler(passwordBox, PasswordBox_Pasting); } else { passwordBox.PreviewKeyDown -= PasswordBox_PreviewKeyDown; DataObject.RemovePastingHandler(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(); } } ``` 在上述代码,我们创建了一个名为IsCopyPasteEnabled的附加属性,并使用PreviewKeyDown事件和DataObject的Pasting事件来禁止复制和粘贴操作。 2. 在XAML将该附加属性应用于PasswordBox控件。 ```xml <PasswordBox local:PasswordBoxHelper.IsCopyPasteEnabled="False" /> ``` 通过将IsCopyPasteEnabled属性设置为"False",我们禁用了PasswordBox控件的复制和粘贴操作。 这样,你可以在不使用自定义控件的情况下禁止PasswordBox的复制和粘贴功能。 希望对你有所帮助!如果还有其他问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值