来自帖子WPF:如何以编程方式从文本框中删除焦点 https://stackoverflow.com/questions/2914495/wpf-how-to-programmatically-remove-focus-from-a-textbox,我知道如何设置TextBox
使用以下代码将焦点返回到其父级:
// 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);
有没有什么方法可以概括此代码(如模板函数),使其也适用于其他项目,例如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,而 FrameworkElement 又继承自 DependencyObject。所以你可以设置ctrl
您想要的任何类型的控件:ComboBox
, TextBox
, Button
, Canvas
, etc.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)