开发者

How do I have a Silverlight databinding update the model as the user types?

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 doe开发者_开发知识库s 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜