Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 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

question from:https://stackoverflow.com/questions/2052389/wpf-reset-focus-on-button-click

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

1 Answer

0 votes
by (71.8m points)

The problem is that the toolbar places your button in a different FocusManager.FocusScope. That means that both the Button and the TextBox can receive logical focus at the same time, each in its own scope. This is normally a good thing, since you usually don't want to lose focus in your main window area when you select menu items and ToolBar buttons, but in your case it is preventing what you are doing from working.

Although you could override the FocusManager.IsFocusScope property on the toolbar and get the effect you want, this is probably not the best plan since it would make all the other toolbar buttons also steal focus from your main window area.

Instead you could use one of several easy solutions:

  • Put your button outside the Toolbar
  • Add a Focusable="true" control to your main window area and focus it when the button is clicked
  • Manually force the update by calling textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource()
  • Temporarily set Focusable="true" on a control in the main window, set focus to it, then immediately set Focusable="false" again

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...