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!