简体   繁体   中英

WPF TextBox Focus on constructor

I'm having a problem focusing on a Control within a Window in WPF.

On the constructor of the Window I add a TextBox as follows:

TextBox tb = new TextBox();
tb.Text = input;
tb.SelectAll();
tb.Focus();

I also call the Focus() method again on the Window loaded event.

The problem is that sometimes the window focuses and other times it does not! This is very strange behavior and I was wondering if someone has had the same problem and might be able to give me some guidance.

-- UPDATE

I have found what is causing the problem but no solution yet. I am using WIA to scan a document, this brings up a ProgressBar which makes my entire application lose focus.

I have tried calling Application.Current.MainWindow.Focus() but this does not restore focus, any suggestions?

From memory, I think the last call on window creation is the Windows.Activated event. You could try running your focus code on that event?

Like I mentioned in my updated question my entire application loses focus due to another dialog being displayed, what I ended up using was:

Application.Current.MainWindow.Activate();

This returns focus to my application and when my Window with the TextBox is shown, Focus is applied to this control.

Hope it helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM