TreeView auto-selecting parent after user selects child

自作多情 提交于 2019-12-01 10:48:44
GameAlchemist

The core issue is to have a Focus() change within an event handler. Postpone the Focus by calling it within a BeginInvoke.

Something like:

delegate void voidDelegate();

private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    var tree = (TreeView)sender;
    var selectedItem = tree.SelectedItem as Child;
    if (selectedItem != null)
    {
        int selectionStart = scriptTextBox.SelectionStart;
        string selectedText = selectedItem.Name;
        voidDelegate giveFocusDelegate = new  voidDelegate(giveFocus);  
        Dispatcher.BeginInvoke(giveFocusDelegate, new object[] { });
        scriptTextBox.SelectedText = selectedText;         
    }
}

private void giveFocus()
{
    scriptTextBox.Focus();
}    

Should get you closer from your goal.

Edit : How do we know this will work ?

As the documentation for Dispatcher.BeginInvoke says :

The operation is added to the event queue of the Dispatcher at the specified DispatcherPriority.

So whatever the priority of the task where you call beginInvoke, the nearest time when the call can happen is right after the execution of current operation ended : the beginInvoked operation is 'pushed' somewhere on the queue of the dispatcher, which works on a single thread.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!