unselecting and reselecting a TreeViewItem in a TreeView

做~自己de王妃 提交于 2019-12-11 12:06:37

问题


I've got the following problem:

In my TreeView i added unselect functionality by calling my own deselect()-method when the user clicks the TreeView but not a TreeViewItem. Here is my TreeView method:

public void deselectAll()
{
    TreeViewItem item = SelectedItem as TreeViewItem;
    if (item != null)
    {
        this.Focus();
        item.IsSelected = false;
    }
}

My problem is, that i can't reselect a TreeViewItem after i unselected it. I've read, that focusing the TreeView itself should solve this problem, but it's not. It also doesn't matter if i put the 'Focus()' before or after the 'IsSelected = false'.

Does anyone has an idea why this is not working? Any thoughts would be appreciated.


回答1:


after you set item.IsSelected = false; you have to call .Focus() for your treeview.

        <TreeView MouseLeftButtonDown="TreeView_MouseLeftButtonDown">
            <TreeViewItem Header="Employee1">
                <TreeViewItem Header="Jesper"/>
                <TreeViewItem Header="Aaberg"/>
                <TreeViewItem Header="12345"/>
            </TreeViewItem>
            <TreeViewItem Header="Employee2">
                <TreeViewItem Header="Dominik"/>
                <TreeViewItem Header="Paiha"/>
                <TreeViewItem Header="98765"/>
            </TreeViewItem>
        </TreeView>

    private void TreeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var tv = sender as TreeView;

        if (tv != null)
        {
            var item = (TreeViewItem)tv.SelectedItem;
            item.IsSelected = false;
            tv.Focus();
        }
    }

you wrote focus() dont solve your problem. where do you call your deselectAll()?

as a workaround you can use the MouseLeftDown to set an item as selected.

ps: dont forget to mark an answer as an anwser.



来源:https://stackoverflow.com/questions/5389797/unselecting-and-reselecting-a-treeviewitem-in-a-treeview

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