WPF PasswordBox控件的使用

WPF PasswordBox并不能像TextBox一样直接使用Binding

 

 需要用到依赖属性。

在项目里新建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);
            }
        }
    }
复制代码

 

LoginView.xaml代码:

复制代码

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

复制代码

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

 

over!

 

posted @   xujimeng  阅读(329)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示