How to block the focus of a control from advancing to the next control in wpf

0

I am developing a small application in wpf and a simple validation, what I want is that when the control does not satisfy the validation, the focus of the control is not removed even though the user clicks on another control. I forced that it does not leave the control until you enter the correct values.

This in Windows Forms is achieved through the validating event that uses the CancelEventArgs class and with the instruction e.Cancel = true; because the focus is blocked to advance to the next control.

The problem is that the WPF controls does not have the Validating event to use that class.

    
asked by Joab Svante HuancaLlave 11.11.2017 в 19:55
source

2 answers

1

Reading your comment to another answer I see that you are using the event LostFocus of TextBox . Effectively, trying to set the focus on an element within its own LostFocus causes an exception of StackOverFlow , probably because it gets into an infinite loop of losing the focus and going back to recover it. This is typically solved by creating a delegate and using Dispatcher.BeginInvoke :

private void Txt_Nombre_LostFocus(object sender, RoutedEventArgs e)
{
    var text = (sender as TextBox);
    if (!noEsVálido)
    {
        var restoreFocus = (System.Threading.ThreadStart)delegate { text.Focus(); };
        Dispatcher.BeginInvoke(restoreFocus);
    }
}

I would not recommend using that system anyway. In my opinion at the user level it is not very comfortable, and it is more logical to validate all the data when confirming the form, but it is a personal opinion.

    
answered by 13.11.2017 / 10:32
source
0

One thing I can think of is to capture the Lost focus event, and return the focus if the validation is not fulfilled.

    
answered by 12.11.2017 в 02:45