【问题标题】:Focusing TreeViewElement after Refresh刷新后聚焦 TreeViewElement
【发布时间】: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()));

标签: c# wpf treeview focus


【解决方案1】:

我有一个在 TreeView 中选择 TreeNode 后操作其他控件的应用程序。该过程完成后,TreeNode 仍处于选中状态,但 TreeView 已失去焦点。

基于 Huv 在他们上面的 cmets 中的方法,我发现以下产生了所需的结果(以 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()
}

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 2018-04-30
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多