WPF: How to programmatically remove focus from a T

2019-01-10 10:35发布

I want to add a simple (at least I thought it was) behaviour to my WPF TextBox.

When the user presses Escape I want the TextBox he is editing to have the text it had when the user started editing, AND I want to remove the focus from the TextBox.

I don't have any problem setting the text for the value it had in the beginning of the edit.

The problem is to remove the focus of the element. I don't want to move the focus to any other component, I just want the TextBox to lose focus. Will I have to have an invisible element to set the focus so my TextBox can lose focus?

6条回答
三岁会撩人
2楼-- · 2019-01-10 10:55

A bit late to the party, but it was helpful to me so here it goes.

Since .Net 3.0, FrameworkElement has a MoveFocus function which did the trick for me.

查看更多
来,给爷笑一个
3楼-- · 2019-01-10 11:05

AFAIK, it is not possible to completely remove the focus. Something in your Window will always have the focus.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-10 11:08

in .NET Framework 4 just Keyboard.ClearFocus();

查看更多
老娘就宠你
5楼-- · 2019-01-10 11:09

In Windows Phone Development, I just did Focus() or this.Focus() in the PhoneApplicationPage and it worked like a charm.

查看更多
狗以群分
6楼-- · 2019-01-10 11:10

The code I have been using :

// Move to a parent that can take focus
FrameworkElement parent = (FrameworkElement)textBox.Parent;
while (parent != null && parent is IInputElement && !((IInputElement)parent).Focusable)
{
    parent = (FrameworkElement)parent.Parent;
}

DependencyObject scope = FocusManager.GetFocusScope(textBox);
FocusManager.SetFocusedElement(scope, parent as IInputElement);
查看更多
我想做一个坏孩纸
7楼-- · 2019-01-10 11:16

You can set the focus to a focusable ancestor. This code will work even if the textbox is inside a template with no focusable ancestors inside that same template:

DependencyObject ancestor = textbox.Parent;
while (ancestor != null)
{
    var element = ancestor as UIElement;
    if (element != null && element.Focusable)
    {
        element.Focus();
        break;
    }

    ancestor = VisualTreeHelper.GetParent(ancestor);
}
查看更多
登录 后发表回答