在做登陆框的时候使用到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!
标签:控件,PasswordChanged,string,passwordBox,static,PasswordBox,WPF,Password From: https://www.cnblogs.com/Xujimeng/p/17655448.html