James
James

Reputation: 2600

enter press doesn't raise property changed event wpf

In my view, there's a TextBox and a Button, the Text property of the TextBox bind to a public property in ViewModel, when user click the button, get the text in the TextBox. I also set the IsDefault property of the Button to true, so that I can press enter to fire the click event. My project uses MVVM, so the command of the button also in the ViewModel. Now, the problem is, I I click the button, I can get the text in TextBox, but if I press enter button, I couldn't get the text, it always null. I set breakpoints and found, if I enter some text in textbox and click button, the RaisePropertyChanged event will be fired, but if I press button, it doesn't. Any one can help?

Thanks!

Upvotes: 3

Views: 2895

Answers (3)

Guttsy
Guttsy

Reputation: 2119

I've amended blindmeis' answer to set focus back to the control that originally had focus.

EventManager.RegisterClassHandler(typeof(Button), ButtonBase.ClickEvent, new RoutedEventHandler((sender, args) =>
{
    var btn = sender as Button;
    if (btn == null || ReferenceEquals(btn, Keyboard.FocusedElement))
        return;

    var originalFocus = Keyboard.FocusedElement;
    btn.Focus();
    if (originalFocus != null && originalFocus.Focusable)
        originalFocus.Focus();
}));

Upvotes: 0

blindmeis
blindmeis

Reputation: 22445

i use this approach to get this work. simply add an eventhandler to your app.xaml.cs OnStartUp()

    EventManager.RegisterClassHandler(typeof (Button), ButtonBase.ClickEvent, new RoutedEventHandler(ButtonClick));

    private void ButtonClick(object sender, RoutedEventArgs e)
    {
        if (sender != null && sender is Button)
        {
            (sender as Button).Focus();
        }
    }

Upvotes: 3

Mike Zboray
Mike Zboray

Reputation: 40838

By default TextBox only updates the property bound to Text when focus is lost. You have two options, either induce a focus change (which can be annoying for a user) or change this behavior.

To change the behavior, modify the UpdateSourceTrigger property of the TextBox binding to PropertyChanged:

<TextBox Text={Binding Path=MyTextProperty, UpdateSourceTrigger=PropertyChanged}/>

This may or may not work for you depending on how much work you are doing on each property change. In some scenarios, it can significantly decrease performance. If that is the case, I would suggest reworking your view model code to do less work when the property changes.

Upvotes: 6

Related Questions