Using event in WPF

Posted by  Brad Pitt
 1714  View(s)
Rate this:
Hi Expert,

I have created two textboxes in WPF named is txt1 and txt2

I have written following line of code on txt1 lostFocus event

If txt1.Text is nothing then 
End If

on txt2 lostFocus event

If txt2.Text is nothing then
End If

Now, If txt1 and txt2 are both empty and user presses TAB key in txt1 the problem occurs. Program goes in infinite loop. I mean cursor comes to txt1 and goes to txt2 infinite times.I know This is normal behavior according to my code.

So I want to have validating event to avoid the problems like above. But I cannot find one in WPF. So which event should I use?

Thanks in advance for any recommendations or solutions.
  1. Re: Using event in WPF

    Hi Brad,

    You can try as following

    Add event handler for event PreviewLostKeyboardFocus. inside the event handler set e.Handled to true if the text is empty. Sample C# code.Below I have writer a generic handler.

    private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        if (string.IsNullOrEmpty((sender as TextBox).Text))
            e.Handled = true;

    I hope it helpful for you.