WPF PasswordBox控件的使用

发布时间 2023-08-24 23:20:19作者: xujimeng

在做登陆框的时候使用到PasswordBox,PasswordBox不能像TextBox一样直接Binding就可以实现MVVM,需要用到依赖属性。

 

 

LoginView文件的代码:

<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="5">
<TextBlock Text="Username:" Width="65" VerticalAlignment="Center"/>
<TextBox Width="200"
Height="30"
VerticalContentAlignment="Center"
Text="{Binding Username}"/>
</StackPanel>

<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="5">
<TextBlock Text="Password:" Width="65" VerticalAlignment="Center"/>
<PasswordBox x:Name="Password"
Width="200"
Height="30"
VerticalContentAlignment="Center"
local:PasswordBoxHelper.Password="{Binding Password, Mode=TwoWay}"/>
</StackPanel>

在项目里新建PasswordBoxHelper.cs文件

public static class PasswordBoxHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxHelper), new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));

        public static string GetPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject obj, string value)
        {
            obj.SetValue(PasswordProperty, value);
        }

        private static void OnPasswordPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is PasswordBox passwordBox)
            {
                passwordBox.PasswordChanged -= PasswordBox_PasswordChanged;
                passwordBox.PasswordChanged += PasswordBox_PasswordChanged;
            }
        }

        private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (sender is PasswordBox passwordBox)
            {
                SetPassword(passwordBox, passwordBox.Password);
            }
        }
    }

 

这样在就能将PasswordBox里的值传递到ViewModel了。

 

over!