如何在用户键入时使用Silverlight数据绑定更新模型?

Nid*_*ocu 2 data-binding silverlight mvvm command-pattern silverlight-4.0

我目前正在使用Silverlight 4并遵循MVVM模式.我有登录框绑定到我的ViewModel,如下所示:

<PasswordBox Password="{Binding Path=Password, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)

然后,我有一个绑定到Command的按钮,该按钮监听ViewModel的PropertyChanged事件,当其中一个数据绑定更新其数据时,它会检查是否有足够的数据来启用Login按钮.

但是,PropertyChanged事件仅在用户从其中一个控件更改焦点时触发,我希望每次按键都更新模型,以便尽快启用登录按钮.

PL.*_*PL. 5

创建一个行为:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并修改你的xaml:

<PasswordBox Password="{Binding Password, Mode=TwoWay}">
    <i:Interaction.Behaviors>
        <local:UpdateSourceOnPasswordChanged/>
    </i:Interaction.Behaviors>
</PasswordBox>
Run Code Online (Sandbox Code Playgroud)

现在,属性密码将更新为用户类型.