Listbox item stay focused after selection
I don't know if the title express what I want. I hav开发者_JAVA技巧e a ListBox in WPF where I generate many elements. When I click on a element while still generating I want my selected item to not move down the list, so I cannot see it anymore, I want to stay in the exact position where I click on it.
If this is possible, can someone point some ideas on how to do it in C#?
Thanks.
Assuming that this is even a good idea and that you are using winforms
Step 1:
Determine the index of the selected item in the source.
Step 2:
When your adding items to the ListBox
split the ListBox
at the index where the item previously was insert the item at that point, then add on the remainder of the items, while making sure that you've removed the item if it is now elsewhere in the list.
Code:
//Let's assume that you know how to get the position of the item when it is clicked and save the //item to a variable called OriginalItem
public void PutTheItemInTheSameSpot()
{
var listboxitems = (List<Integer>)YourListBox.DataSource;
var originalClikedItem = OriginalItem;
var topPart = new List<Integer>();
for (i = 0; i < itemPosition; i++)
{
topPart.Add(listboxItems[i]);
}
topPart.Add(originalClickedItem);
var bottomPart = listboxitems.Remove(toppart);
YourListBox.DataSource = toppart.AddRange(bottomPart);
}
Saw your edit about it being WPF
The could should work in idea.
Just a thought: you could try having your view respond to an event whenever an item is added to your ListBox. In the event handler, you could force the selected item to scroll into view presumably keeping it in the current "viewable" position:
listBox.ScrollIntoView(listBox.SelectedItem);
I've never tried this before so it may or may not produce the desired affect?
精彩评论