tags:

views:

479

answers:

3

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.

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)).

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?

+1  A: 

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

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

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

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.

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

Henk Holterman
Good point, I'll clarify...
willem
A: 
this.Dispatcher.BeginInvoke((Action)delegate
{
    txtToken.SelectAll();
    txtToken.Focus();
});
Oleg Mihailik
A: 

Can't vote yet, but Oleg's answer is obviously the solution. Works fine for me, and much more elegant.

Daniel Stolt