Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

c# - WPF Reset Focus on Button Click

I have a TextBox and a ToolBar with a Button. If I'm typing in the TextBox and I click the Button I want the TextBox to lose Focus so the binding gets updated. I don't want to add a UpdateSourceTrigger=PropertyChanged to my TextBox. But instead when I click on the Button I reset Focus to the main window so what ever I'm on loses Focus and updates the bindings.

I've tried adding a OnClick to the button with the following, but it doesn't seem to work:

    private void Button_Click(object sender, RoutedEventArgs e) {
        FocusManager.SetFocusedElement(this, null);
    }

Any tips would be appreciated.

Thanks, Raul

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I encountered a similar issue. I need to unfocus a textbox when enter is pressed. I end up with this code:

var scope = FocusManager.GetFocusScope(elem); // elem is the UIElement to unfocus
FocusManager.SetFocusedElement(scope, null); // remove logical focus
Keyboard.ClearFocus(); // remove keyboard focus

I think it is cleaner than creating dummy controls and it is reusable. I'm not confident with this solution though. But it seems work well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...