更新列表框而不丢失所选项目,WPF [英] Updating listbox without losing selected item, WPF

查看:68
本文介绍了更新列表框而不丢失所选项目,WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表框每秒钟更新一次,在工作期间,我需要选择其中的一些项并执行命令,这是不可能的,因为列表框已更新并且丢失了它的选定项.

Listbox is updated every sec and during work I need to select some of it's items and execute a command, which is impossible, because listbox is updated and loses it's selected item.

ObservableCollection是我列表的ViewModel.

ObservableCollection is the ViewModel of my list.

我有一些选择,也许有更好的解决方案:

I have some options in mind and perhaps there are better solutions:

  1. 检测要传播的列表中的新项目,并将新项目添加到ObservableCollection中,而无需重新初始化ObservableCollection

  1. Detect new items in the list to be propagated and add new items to ObservableCollection without reinitializing ObservableCollection

检测旧项目中的更改并在必要时更新其字段.

Detect changes in the old items and updated their fields if necessary.

这有点麻烦,尽管并不困难,但是还有其他选择吗?

This is somewhat cumbersome, though not difficult, but are there any other options?

更新,我拥有的解决方案

我选择了3-d部分:在开始更新之前,我保存了已排序集合的选定索引,并加载了一个新集合并比较了旧集合.我知道,这不是很有效,但是对于当前应用程序来说,它非常合适:集合永远不会超过数百个,通常不会超过100个.集合的每个元素都支持急切和延迟加载.并且,如果有更改的项目,它们将从服务器加载其内容,而其他项目则保持不变.然后,我更新可观察的集合,从服务器更新更改的项目,并在视图模型中设置选定的索引.手动选择一个项目可以解决更新后失去焦点的问题.

I've chosen the 3-d part: before an update has started, I save selected index of sorted collection and load a new collection and compare vs. old collection. I Know, this is not efficient, but for the current application this fits quite well: collections will never be more than some hundreds, ordinarily, no more 100. Each element of collection supports eager and lazy loading. And if there are changed items, they load their content from server, while other remain intact. And then I update observable collection, update changed items from server and set selected index in the viewmodel. Selecting an item manually solves the problem of losing focus after update.

推荐答案

在更新列表之前,请保存所选项目的密钥. 在列表的新版本中找到它,然后重新选择它. 不要依赖原始参考,并允许其他人从新列表中删除它以供选择.

Save the selected item's key before the list is updated. Find it in the new version of the list, and re-select it. Don't rely on the original reference, and allow for some other fellow removing it from the new list to select from.

这篇关于更新列表框而不丢失所选项目,WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆