题
我刚开始使用M-V-VM和WPF和了解一些有约束力的问题,有问题。
我有具有ComboBox
和PasswordBox
登录页面。所述ComboBox
看起来像这样:
<ComboBox Name="comboBox1" SelectedItem="{Binding Path=Username}">
这工作就好了 - !我的价值观得到更新,每次在SelectedItem
的ComboBox
修改
在我的视图模型我有使用这种方法的ICommand
以确定是否登录按钮处于活动状态:
public bool CanLogin()
{
return !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password);
}
所以我的问题是我没有绑定到视图模型Password属性的PasswordBox
- 所以我没有办法知道,当它被更新
那么,如何让PasswordBox
的到我的视图模型的价值?我读过的一切只是说,不绑定出于安全原因PasswordBox
。我将简单地摘下的CanLogin(密码限制),但我需要的值以沿着到的AccountService通过。
解决方案
有趣。
看这个博客帖子,看看它是否帮助你。 http://blog.functionalfun.net/2008/06 /wpf-passwordbox-and-data-binding.html
显然的链路是死现在所以这里原始溶液(实测这里):
可以使用附加属性来创建这样的助手:
public static class PasswordHelper { public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordHelper), new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged)); public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach)); private static readonly DependencyProperty IsUpdatingProperty = DependencyProperty.RegisterAttached("IsUpdating", typeof(bool), typeof(PasswordHelper)); public static void SetAttach(DependencyObject dp, bool value) { dp.SetValue(AttachProperty, value); } public static bool GetAttach(DependencyObject dp) { return (bool)dp.GetValue(AttachProperty); } public static string GetPassword(DependencyObject dp) { return (string)dp.GetValue(PasswordProperty); } public static void SetPassword(DependencyObject dp, string value) { dp.SetValue(PasswordProperty, value); } private static bool GetIsUpdating(DependencyObject dp) { return (bool)dp.GetValue(IsUpdatingProperty); } private static void SetIsUpdating(DependencyObject dp, bool value) { dp.SetValue(IsUpdatingProperty, value); } private static void OnPasswordPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { PasswordBox passwordBox = sender as PasswordBox; passwordBox.PasswordChanged -= PasswordChanged; if (!(bool)GetIsUpdating(passwordBox)) { passwordBox.Password = (string)e.NewValue; } passwordBox.PasswordChanged += PasswordChanged; } private static void Attach(DependencyObject sender, DependencyPropertyChangedEventArgs e) { PasswordBox passwordBox = sender as PasswordBox; if (passwordBox == null) return; if ((bool)e.OldValue) { passwordBox.PasswordChanged -= PasswordChanged; } if ((bool)e.NewValue) { passwordBox.PasswordChanged += PasswordChanged; } } private static void PasswordChanged(object sender, RoutedEventArgs e) { PasswordBox passwordBox = sender as PasswordBox; SetIsUpdating(passwordBox, true); SetPassword(passwordBox, passwordBox.Password); SetIsUpdating(passwordBox, false); } }
使用它:
<PasswordBox w:PasswordHelper.Attach="True"
w:PasswordHelper.Password="{Binding Text, ElementName=plain, Mode=TwoWay}"
Width="100"/>
其他提示
我发布了GIST 此处这是一个可绑定密码框。
不隶属于 StackOverflow