在 TreeView 中取消选择和重新选择 TreeViewItem [英] unselecting and reselecting a TreeViewItem in a TreeView
问题描述
我遇到了以下问题:
在我的 TreeView 中,当用户单击 TreeView 而不是 TreeViewItem 时,我通过调用我自己的 deselect() 方法添加了取消选择功能.这是我的 TreeView 方法:
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;
}
}
我的问题是,在取消选择 TreeViewItem 后,我无法重新选择它.我读过,关注 TreeView 本身应该可以解决这个问题,但事实并非如此.如果我将 'Focus()' 放在 '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.
推荐答案
after you set item.IsSelected = false;你必须为你的树视图调用 .Focus().
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();
}
}
你写的 focus() 没有解决你的问题.你在哪里调用你的 deselectAll()?
you wrote focus() dont solve your problem. where do you call your deselectAll()?
作为一种解决方法,您可以使用 MouseLeftDown 将项目设置为选中状态.
as a workaround you can use the MouseLeftDown to set an item as selected.
ps:不要忘记将答案标记为 anwser.
ps: dont forget to mark an answer as an anwser.
这篇关于在 TreeView 中取消选择和重新选择 TreeViewItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!