WPF ListBox 在失去焦点后将焦点设置为第一个项目
问题: 我在管理带有嵌入式列表框的 WPF 列表框中的焦点和项目选择以及后面代码中的一些自定义选择管理时遇到问题。
背景: “父”ListBox
被分配一个包含“子”ListBox
的 DataTemplate
。我添加了代码,以使用向上和向下箭头键从父 ListBoxItem
导航到子项目,以及从子项目返回到父项目。
当导航回父项(不是第一级列表框中的第一项)时,焦点始终设置为第一项,并且即使在程序中将其设置为非项,也会选择该项。 -第一项(例如父项#2)。我跟踪了代码,焦点和选择设置为非第一个项目,但总是收到另一个选择并将焦点设置为第一个项目的事件。
stackoverflow上还有一个案例和我遇到的情况类似。案例是 wpf listview 失去了焦点 我尝试了这种情况下的所有答案和响应,但没有一个起作用。
有人知道为什么我无法以编程方式选择父 ListBox
中的非第一个元素吗?
Problem:
I'm having trouble managing focus and item selection in a WPF ListBox with an embedded ListBox and some custom selection management in the code behind.
Background:
The "parent" ListBox
is assigned a DataTemplate
containing a "child" ListBox
. I have added code to navigate using the up and down arrow keys from the parent ListBoxItem
to the child items and from the child items back to the parent items.
When navigating back to a parent item which is not the first item in the first level list box the focus is always set to the first item and it is selected even though it is set in the program to a non-first item (e.g. parent item #2). I have traced through the code and the focus and selection is set to a non-first item but then another event to select and set the focus to the first item is always received.
There was another case on stackoverflow which was similar to what I am experiencing. The case is wpf listview lost the focus I tried all of the answers and responses in this case and none of them worked.
Does anyone have insight into why I can't programmatically select a non-first element in the parent ListBox
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用
ListBox.IsSynchronizedWithCurrentItem = true
然后使用列表的集合视图(如果您没有显式创建集合视图,则可以使用CollectionViewSource.GetDefaultView
)来设置当前项(ICollectionView.MoveCurrentTo()
)。在使用集合视图时,选择器有一种更好的方法来处理选定的项目,而不是
SelectedItem
。Try using
ListBox.IsSynchronizedWithCurrentItem = true
then working with the list's collection view (if you're not explicitly creating one, you can useCollectionViewSource.GetDefaultView
) to set the current item (ICollectionView.MoveCurrentTo()
).Selectors have a much more preferable method of dealing with selected items when working with the collection view, rather than
SelectedItem
.我也一直在努力解决列表框中的焦点问题。也许这两个问题的答案会对您有进一步的帮助。特别是将焦点设置在后台线程上的技巧非常有用。
取消选择列表框中的项目
延迟焦点更改
I have been struggling with the Focus in ListBoxes too. Perhaps the answers to these two questions will help you further. Especially the trick with setting the focus on a Background thread is very very useful.
Deselect item in ListBox
Delay change of focus