Refresh data in ListBox - stop moving the scrollbar and flashed selected item
I try solve this problem. In WFP app I bind binadble collection to the property ItemSource of listBox.
Property signature is:
public BindableCollection<UserInfo> Friends
{
get { return _friends; }
set
{
_friends = value;
NotifyOfPropertyChange(() => Friends);
}
}
UserInfo class consit property:
- BitmapImage ProfilePhoto {get;set;}
- String Nick{get;set}
- String Status{get;set;} //offline, online, chatting
- String ChatRoom{get;set;} //name of chat room where user chatting
I get every 10 seconds new fresh data as IDictionary => ().
I need refresh data in listbox. So I try this:
private void RefreshContactsData(IEnumerable<KeyValuePair<string, UserInfo>> freshFriends)
{
//store selected item in listBox
var tempSelectedFriend = SelectedFriend;
//store selecte index in listbox
var tempSelectedIndex = SelectedFriendsIndex;
//Clear property which is binded on listBox ItemSource
Friends.Clear();
foreach (var freshFriend in freshFriends)
{
freshFriend.Value.IsFriend = true;
//Add fresh data
Friends.Add(freshFriend.Value);
}
StayInRoom();
//set
SelectedFriend = tempSelectedFriend;
SelectedFriendsIndex = tempSelectedIndex;
}
Problems is:
I store current current selected item in listBox, clear listbox, add new data, and set back selected item in listbox. But user see that scrollbar is moved and moved back and also selected item flashed.
How can I remove this unwanted b开发者_StackOverflowehavior.
I expect that the issue is your SelectedFriend
property refers to a reference which no longer exists when your collection is repopulated. Is there any property on UserInfo which uniquely identifies a user? (Nick
?). You could store this selected value instead, and then after repopulating the collection, find and set SelectedFriend
to the item whose Nick
matches the stored value.
To prevent listbox scrollbar jumping do not remove then add back all items from the BindableCollection.
Rewrite RefreshContactsData to:
- Delete items that exist in Friends that no longer exist in freshFriends.
- Add items that exist in freshFriends that do not exist in Friends.
- Update existing items in Friends and freshFriends.
You may need to implement INotifyPropertyChanged on UserInfo.
精彩评论