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!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?