WPF: Listbox, centering selected item

2020-04-08 07:01发布

问题:

Is it possible to always keep selected item in the middle of a listbox? If the user selects an item, I want to scroll so that the newly selected item is in the middle.

I guess it want be possible for the 'edge cases' (the first and last few items), but that's ok.

回答1:

David Anson posted some articles on his blog that might help you here: Part 1 and Part 2. He gives an extension method that centers an item in an List Box. You might be able to build on that.



回答2:

It is possible with couple of lines of custom code. Here's a discussion of a sample implementation. You might need to tweak it a bit to account for even number of items, insted of only odd number, but the general idea is the same.