Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当从codebehind聚焦时,如何选择WPF文本框中的所有文本?_Wpf_Textbox_Selection_Onfocus - Fatal编程技术网

当从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

我想从codebehind设置WPF
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中被选择。。