PasswordBox with MVVM

前端 未结 5 951
情深已故
情深已故 2020-12-16 11:59

Hi people stackoverflow. I\'m working with MVVM, I have ViewModel call UserViewModel with a Property Password. In the View have a control P

5条回答
  •  情话喂你
    2020-12-16 12:22

    There is an issue with the BindablePasswordBox. It only works in one direction, PasswordBox to PasswordProperty. Below is a modified version of it that works in both directions. It registers a PropertyChangedCallback and updates the PasswordBox's Password when it is called. I hope that someone finds this useful.

    public class BindablePasswordBox : Decorator
    {
        public static readonly DependencyProperty PasswordProperty = DependencyProperty.Register("Password", typeof(string), typeof(BindablePasswordBox), new PropertyMetadata(string.Empty, OnDependencyPropertyChanged));
        public string Password
        {
            get { return (string)GetValue(PasswordProperty); }
            set { SetValue(PasswordProperty, value); }
        }
    
        private static void OnDependencyPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
        {
            BindablePasswordBox p = source as BindablePasswordBox;
            if (p != null)
            {
                if (e.Property == PasswordProperty)
                {
                    var pb = p.Child as PasswordBox;
                    if (pb != null)
                    {
                        if (pb.Password != p.Password)
                            pb.Password = p.Password;
                    }
                }
            }
        }
    
        public BindablePasswordBox()
        {
            Child = new PasswordBox();
            ((PasswordBox)Child).PasswordChanged += BindablePasswordBox_PasswordChanged;
        }
    
        void BindablePasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            Password = ((PasswordBox)Child).Password;
        }
    }
    

提交回复
热议问题