在WPF中,当选择TreeViewItem时,如何关注另一个控件但仍然完成我的TreeViewItem选择?

时间:2020-11-25 14:14:23

This sounds like a tricky question... let me ellaborate...

这听起来像一个棘手的问题......让我精心设计......

I have a treeView. When a treeViewItem is clicked/selected, I would like another TextBox to be focused.

我有一个treeView。当单击/选择treeViewItem时,我希望另一个TextBox被聚焦。

The problem is that as soon as I add code to Focus the Textbox, it looks like the TreeView does not Show its selected node anymore (i.e. the treeItem is not Selected at all (or at least not visibly)).

问题是,只要我将代码添加到Focus the Textbox,就会看起来TreeView不再显示其所选节点(即,TreeItem根本没有被选中(或者至少不是可见的))。

Here is my event handling code...

这是我的事件处理代码......

    private void trvTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        grpEditTreeItem.DataContext = (TreeItemDefinition)e.NewValue;


        txtToken.SelectAll();
        txtToken.Focus();
    }

Any ideas?

2 个解决方案

#1


Distinguish between Selected and Focused. You cannot have more than 1 Control focused at any one time.

区分选定和聚焦。任何时候都不能有超过1个控制。

What you want is your TreeView to Show it's selectednode when it has lost the focus.

你想要的是你的TreeView在它失去焦点时显示它的selectednode。

Edit:
But I can confirm the problem, setting the Focus to another Control inside SelectedItemChanged() will Cancel the selection.

编辑:但我可以确认问题,将Focus设置为SelectedItemChanged()内的另一个控件将取消选择。

So what you need is something to postpone the Focus() call. A rough (but not ideal) solution is to place txtToken.Focus() in a trvTree_MouseUp() event handler. But that will also take the Focus away when expanding a Node for example.

所以你需要的是推迟Focus()调用。粗略(但不理想)的解决方案是将txtToken.Focus()放在trvTree_MouseUp()事件处理程序中。但是,例如,当扩展节点时,这也会使焦点消失。

So you will probably have to use a one-shot timer fired from SelectedItemChanged() .

因此,您可能必须使用从SelectedItemChanged()触发的一次性计时器。

#2


this.Dispatcher.BeginInvoke((Action)delegate
{
    txtToken.SelectAll();
    txtToken.Focus();
});

#1


Distinguish between Selected and Focused. You cannot have more than 1 Control focused at any one time.

区分选定和聚焦。任何时候都不能有超过1个控制。

What you want is your TreeView to Show it's selectednode when it has lost the focus.

你想要的是你的TreeView在它失去焦点时显示它的selectednode。

Edit:
But I can confirm the problem, setting the Focus to another Control inside SelectedItemChanged() will Cancel the selection.

编辑:但我可以确认问题,将Focus设置为SelectedItemChanged()内的另一个控件将取消选择。

So what you need is something to postpone the Focus() call. A rough (but not ideal) solution is to place txtToken.Focus() in a trvTree_MouseUp() event handler. But that will also take the Focus away when expanding a Node for example.

所以你需要的是推迟Focus()调用。粗略(但不理想)的解决方案是将txtToken.Focus()放在trvTree_MouseUp()事件处理程序中。但是,例如,当扩展节点时,这也会使焦点消失。

So you will probably have to use a one-shot timer fired from SelectedItemChanged() .

因此,您可能必须使用从SelectedItemChanged()触发的一次性计时器。

#2


this.Dispatcher.BeginInvoke((Action)delegate
{
    txtToken.SelectAll();
    txtToken.Focus();
});