【发布时间】:2013-12-15 12:23:47
【问题描述】:
我在聚焦 TreeViewItem 时遇到问题。 我有一个(一点点优化的)TreeView 并刷新了内容。 视觉上选定的项目保持选中状态,但逻辑上它不是。开头和结尾的 Focus-Check 不一样,但我认为应该。
这是我的代码(所有不工作的重新聚焦的东西):
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 在焦点上做了什么? 有人有想法吗?
【问题讨论】:
-
好的,我明白了。我在这篇文章中找到了提示:stackoverflow.com/questions/1003883/… 独奏是“给 TreeView 一些时间”并使用它来设置焦点: Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() => tv.TryFindNode(selectedContent ).Focus()));