Preventing ListBox scrolling to top when updated

帅比萌擦擦* 提交于 2019-12-01 20:09:44

Nice repro code, I had no trouble diagnosing the source of the problem. It is a feature, not a bug. Press the arrow down key several times, then scroll the list. Note that it doesn't jump back now.

What's going on here is that list box automatically scrolls the item with the focus back into view when it gets updated. This is normally desirable behavior, you cannot turn it off. Workarounds, like selecting the item you're updating, isn't going to be pretty when you update the list like this, it is going to flicker badly. Maybe virtual mode, I didn't try it.

ListView doesn't have this behavior, consider using it instead. Use View = List or Details.

It might be prudent to disable any painting of the Listbox when doing the updates. Use ListBox.BeginUpdate() and then update the entries, when done, invoke ListBox.EndUpdate(). This should ensure that no refreshes occurs during the update.

You should also ensure that you do not refresh the ListBox from a thread either as cross-threading is dis-allowed, and the runtime will barf with a message saying that 'Cross Threading Exception' has occurred.

Use the ListBox's BeginInvoke(...) method to get around the cross threading issue. See here on the MSDN on how this is done.

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