views:

134

answers:

2

I'm currently using Silverlight 4 and following the MVVM pattern. I have login boxes bound to my ViewModel like so:

<PasswordBox Password="{Binding Path=Password, Mode=TwoWay}" />

I then later on have a button bound to a Command which listens to the ViewModel's PropertyChanged event and when one of the databindings has its data updated, it does a check to see if there is now enough data to enable the Login button.

However, the PropertyChanged event only fires when the user changes focus from one of the controls, I'd like the model to be updated with every keystroke so that the login button enables as soon as possible.

A: 

I'd recommend using a behavior that listens for the PasswordBox's OnKeyDown event and fires your ViewModel's event from there (or runs some other piece of custom code that you wanted to attach to the PropertyChanged event). Databinding for TextBoxes and their derivitives (like PasswordBox) don't update until they lose focus, so you have to manually update the binding.

Raumornie
+2  A: 

Create a behavior:

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;
    }
}

And modify your xaml:

<PasswordBox Password="{Binding Password, Mode=TwoWay}">
    <i:Interaction.Behaviors>
        <local:UpdateSourceOnPasswordChanged/>
    </i:Interaction.Behaviors>
</PasswordBox>

Now the property Password will update as user types.

PL
Reading around, this looks like this would work but does it require some kind of additional framework to run? Behaviors aren't a standard Silverlight baseclass as far as I can see.
Nidonocu
http://expressionblend.codeplex.com/
PL
Thanks, got it working and I'm looking at the Behavior system too to see where else it can help me. Thanks!
Nidonocu