将焦点设置回其父级? [英] Set focus back to its parent?
本文介绍了将焦点设置回其父级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从:如何以编程方式从移除焦点文本框,我知道如何使用下面的代码来设置文本框
的焦点回到它的父:
From post WPF: How to programmatically remove focus from a TextBox, I know how to set a TextBox
's focus back to its parent using the following code:
// 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);
有什么办法来概括这段代码(如模板函数),使其也为其他项目工作像组合框
,画布
,图片
等。
Is there any way to generalize this code (like template functions) to make it also work for other items like ComboBox
, Canvas
, Image
etc.
推荐答案
这应该是比较简单的:
FrameworkElement ctrl = control; //or whatever you're passing in, since all controls are FrameworkElements.
// Move to a parent that can take focus
FrameworkElement parent = (FrameworkElement)ctrl.Parent;
while (parent != null && parent is IInputElement
&& !((IInputElement)parent).Focusable)
{
parent = (FrameworkElement)parent.Parent;
}
DependencyObject scope = FocusManager.GetFocusScope(ctrl); //can pass in ctrl here because FrameworkElement inherits from DependencyObject
FocusManager.SetFocusedElement(scope, parent as IInputElement);
这工作,因为所有的控件自FrameworkElement其自DependencyObject继承继承。所以,你可以设置 CTRL
你想要的任何类型的控件:组合框
,文本框
,按钮
,画布
等
This works because all controls inherit from FrameworkElement which inherits from DependencyObject. So you can set ctrl
to any type of control you want: ComboBox
, TextBox
, Button
, Canvas
, etc.
这篇关于将焦点设置回其父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文