2013-12-15 34 views
0

我有一个聚焦TreeViewItem的问题。 我有一个(一点点optimated)TreeView和刷新内容。 视觉上选定的物品保持选中状态,但在逻辑上不是。重点检查在开始和结束时是不一样的,但在我看来他们应该。刷新后聚焦TreeViewElement

这里是我的代码(包括所有非工作重聚的事情):

private void Refresh(string selectedContent) 
{ 
    //Check out the focused element 
    //Returns "System.Windows.Controls.TreeViewItem Header:<my selectedContent-Value>; Items.Count:0" 
    MessageBox.Show(Keyboard.FocusedElement.ToString()); 

    var currentFocus = Keyboard.FocusedElement; 
    tv.Refresh(); //this refreshes the treeview 

    //Not working 
    Keyboard.Focus(currentFocus); 

    //Not working 
    DependencyObject focusScope = FocusManager.GetFocusScope(currentFocus); 
    FocusManager.SetFocusedElement(focusScope, currentFocus); 

    //also not working 
    currentFocus.Focus(); 

    //not working 
    Keyboard.Focus(tv.TryFindNode(selectedContent)); //TryFindNode searches the node in the TreeView and returns it 

    //not working 
    tv.TryFindNode(selectedContent).Focus(); 

    //Check out the focused element 
    //returns "TreeViewTesting.TreeViewTesting" (my class where I'm testing this issue) 
    MessageBox.Show(Keyboard.FocusedElement.ToString()); 
} 

我不明白的是,这个作品:

private void Refresh(string selectedContent) 
{ 
    //Check out the focused element 
    //Returns "System.Windows.Controls.TreeViewItem Header:<my selectedContent-Value>; Items.Count:0" 
    MessageBox.Show(Keyboard.FocusedElement.ToString()); 

    tv.Refresh(); //this refreshes the treeview 

    MessageBox.Show("I'm just a Message to show a messagebox"); 

    tv.TryFindNode(selectedContent).Focus(); 

    //Check out the focused element 
    //Returns "System.Windows.Controls.TreeViewItem Header:<my selectedContent-Value>; Items.Count:0" 
    MessageBox.Show(Keyboard.FocusedElement.ToString()); 
} 

所以,我怎么说,Dummy-Messagebox在做什么? 任何人有想法?

+0

OK,我知道了。 我在这篇文章中发现了提示: http://stackoverflow.com/questions/1003883/treeview-item-loses-selection-when-focus-is-lost?rq=1 该solication是“给TreeView一些时间“,并用它来设置foucs: Dispatcher.BeginInvoke(DispatcherPriority.Input,new Action(()=> tv.TryFindNode(selectedContent).Focus())); – Hunv

回答

0

我有一个应用程序在TreeView中选择TreeNode后操作其他控件。当这个过程完成后,TreeNode仍然被选中,但是TreeView失去了焦点。

基于Hunv在他们的意见的方式上面,我发现下面产生期望的结果(这是TreeView的重点,树节点选择):

private void treeView_AfterSelect(object sender, TreeViewEventArgs e) 
{ 
    ProcessMySelection(); 

    // give the app a chance to 'recover' and keep focus on the TreeView 
    // i don't understand why this works -- is there a better way? 
    Application.DoEvents() 
}