WPF: Get The Next Control Name Focused After Lost Focus

Although "the lost locus" event seems simple, but I've spent a whole day just to code for this do event calculation. What I need is the code to be executed when "control1" is lost focus and goes to "control2".  

However, closing the form and moving from one application to another is also counted as lost focus. This is what causes the error, so I need to know how to get the next control after the lost focus event. And it turns out that it can't be done at the LostFocus event, but at the LostKeyboardFocus event. But this is working fine for me. Because the LostKeyboardFocus event is executed before the LostFocus event, so we can retrieve the variables in the LostKeyboardFocus event to use in the LostFocus event.

Let's see below sample. I have a texbox named TextNo, and I added event for LostFocus and LostKeyboardFocus. 


You can add a variable that can be accessed anywhere on this form. But in this example I will save the name of the next focus control in Textbox1.

Code with C#:

private void TextNo_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    textBox1.Text = ((FrameworkElement)e.NewFocus).Name ; 
}


Code with VB.NET:

Private Sub TextNo_LostKeyboardFocus(ByVal sender As Object, ByVal e As KeyboardFocusChangedEventArgs)
    textBox1.Text = (CType(e.NewFocus, FrameworkElement)).Name
End Sub



Post a Comment

0 Comments