我目前正在使用 Silverlight 4 并遵循 MVVM 模式。我将登录框绑定(bind)到我的 ViewModel,如下所示:
<PasswordBox Password="{Binding Path=Password, Mode=TwoWay}" />
然后,我将一个按钮绑定(bind)到一个命令,该命令监听 ViewModel 的 PropertyChanged 事件,并且当其中一个数据绑定(bind)更新其数据时,它会进行检查以查看现在是否有足够的数据数据以启用登录按钮。
但是,PropertyChanged 事件仅在用户从其中一个控件更改焦点时触发,我希望每次击键时都会更新模型,以便尽快启用登录按钮。
最佳答案
创建行为:
public class UpdateSourceOnPasswordChanged : Behavior<PasswordBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PasswordChanged += OnPasswordChanged;
}
private void OnPasswordChanged(object sender, RoutedEventArgs e)
{
var binding = AssociatedObject.GetBindingExpression(PasswordBox.PasswordProperty);
binding.UpdateSource();
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PasswordChanged -= OnPasswordChanged;
}
}
并修改你的xaml:
<PasswordBox Password="{Binding Password, Mode=TwoWay}">
<i:Interaction.Behaviors>
<local:UpdateSourceOnPasswordChanged/>
</i:Interaction.Behaviors>
</PasswordBox>
现在,属性“密码”将随着用户类型的变化而更新。
关于silverlight - 如何让 Silverlight 数据绑定(bind)在用户键入时更新模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2285011/