有人发现想Password的控件中实现如下的绑定,
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
<UserControl x:Class="SilverlightApplication9.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300" xmlns:o="clr-namespace:SilverlightApplication9">
<UserControl.Resources>
<o:MainController x:Name="mainController" />
</UserControl.Resources>
<StackPanel x:Name="LayoutRoot" Background="White">
<PasswordBox Password="{Binding Path=Password, Source={StaticResource mainController}}" />
<TextBox Text="{Binding Path=Password, Source={StaticResource mainController}, Mode=TwoWay}" />
</StackPanel>
</UserControl>
后代代码:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public class MainController: INotifyPropertyChanged
{
private string password;
public string Password
{
get { return password; }
set
{
if (password != value)
{
password = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Password"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
却总是报错。
原因是PasswordBox的password属性并没有相应的DependencyProperty(依赖属性),所以就不可以实现绑定。
但是你可以暴露出来一个依赖属性,在内存中存储PasswordBox的文本,PasswordBox 可以对他的文本进行加密并且只在调用密码CLR属性时生成普通的文本。
如下所示:
1. 定义一个PasswordBoxHelper 类,并注册一个依赖属性PasswordBind
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
public class PasswordBoxHelper
{
private static readonly DependencyProperty passwordBindProperty =
DependencyProperty.RegisterAttached("PasswordBind", typeof(string), typeof(PasswordBoxHelper),
new PropertyMetadata(PropertyChangedHandler));
private static void PropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
PasswordBox passBox = (PasswordBox)sender;
passBox.Password = (string)e.NewValue;
}
}
2. 你就可以绑定到你的PasswordBox 控件上在xaml代码中:
<PasswordBox o:PasswordHelper.PasswordBind="{Binding Path=Password, Source={StaticResource mainController}}" />
由于使用的绑定方式是OneWay, 所以PasswordBox的Password属性的值只会随着数据源而改变,当用户输入密码时并不能改变数据源绑定的值,因为用户输入的值只是关联到Password的password属性,而不是附加的属性passwordbind。
如果要检查用户的输入,需要使用PasswordBox的事件PasswordChanged。
参考链接:http://www.silverlightissues.com/issue.php5?i=68