Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return focus to a control in WPF from within the lost focus event of the same control?

Tags:

wpf

In my WPF application I am doing some input validation in the lostfocus event of a textbox control. If the text does not meet the correct criteria I clear the text in the textbox. That works fine. What I am having trouble doing is returning focus to the control after viewing a message box. For example when I use the below code, the text box focus method re-triggers the lost focus event after I close the message box.

 private void TaskNameBox_LostFocus(object sender, RoutedEventArgs e)

{

    ... validation logic here

    MessageBox.Show("Message.", "Error", MessageBoxButton.OK);            
    TaskNameBox.Focus();
 }

I don't know why the Focus method would retrigger the lost focus event, but I need a way to get the focus back on the TaskNameBox Control after losing it. Any suggestions would be very much appreciated. I am new to WPF.

like image 404
user3366675 Avatar asked Feb 10 '23 00:02

user3366675


1 Answers

Use it following:

private void TaskNameBox_LostFocus(object sender, RoutedEventArgs e)

{

    ... validation logic here

    MessageBox.Show("Message.", "Error", MessageBoxButton.OK); 

    Dispatcher.BeginInvoke((ThreadStart)delegate
            {
                TaskNameBox.Focus();
            });
 }
like image 194
Nazmul Avatar answered Feb 13 '23 21:02

Nazmul