当从codebehind聚焦时,如何选择WPF文本框中的所有文本?
我想从codebehind设置WPF当从codebehind聚焦时,如何选择WPF文本框中的所有文本?,wpf,textbox,selection,onfocus,Wpf,Textbox,Selection,Onfocus,我想从codebehind设置WPFTextBox的焦点(不是TextBox的codebehind,而是一些父控件),并在收到焦点时从TextBox的codebehind中选择TextBox中的所有文本 我将文本框的焦点如下: var scope = FocusManager.GetFocusScope(txt); FocusManager.SetFocusedElement(scope, txt); private static void SelectAllText(object sende
TextBox
的焦点(不是TextBox
的codebehind,而是一些父控件),并在收到焦点时从TextBox
的codebehind中选择TextBox
中的所有文本
我将文本框的焦点如下:
var scope = FocusManager.GetFocusScope(txt);
FocusManager.SetFocusedElement(scope, txt);
private static void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
然后在TextBox
中收听事件,就像在TextBox
s codebehind中一样:
AddHandler(GotFocusEvent, new RoutedEventHandler(SelectAllText), true);
并尝试选择如下所示的文本:
var scope = FocusManager.GetFocusScope(txt);
FocusManager.SetFocusedElement(scope, txt);
private static void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
但是文本没有被选中。如何修改它以使其正常工作?在选择文本之前,您必须先设置键盘
聚焦于文本框
例如:
private static void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
{
Keyboard.Focus(textBox);
textBox.SelectAll();
}
}
您确定SelectAllText处理程序中的textBox不为空吗?设置断点并单步执行。您可以说文本框
的代码隐藏。如果您的处理程序是实际文本框的实例方法,为什么不直接调用SelectAll()而不是从发送方获取引用?@Steve,我已经检查/尝试过了。文本确实是根据selectedText属性选择的,但无论出于何种原因,它都不会在UI中被选择。。