我有一个关注TreeViewItem的问题。 我有一点(有点看见)TreeView并刷新内容。 视觉上,所选项目保持选中状态但逻辑上不是。在开始和结束时的焦点检查是不一样的,但在我看来他们应该。
这是我的代码(所有非工作重新聚焦的东西):
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 :(得分:0)
我有一个应用程序在TreeView中选择TreeNode后操纵其他控件。完成此过程后,TreeNode仍处于选中状态,但TreeView失去了焦点。
基于Hunv在上面的评论中的方法,我发现以下内容产生了所需的结果(选择了TreeView,选择了TreeNode):
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()
}