C# 刷新列表框中的数据-停止移动滚动条并刷新所选项目

C# 刷新列表框中的数据-停止移动滚动条并刷新所选项目,c#,wpf,listbox,refresh,scrollbar,C#,Wpf,Listbox,Refresh,Scrollbar,我试图解决这个问题。在WFP应用程序中,我将binadble集合绑定到listBox的属性ItemSource 财产签名为: public BindableCollection<UserInfo> Friends { get { return _friends; } set { _friends = value; NotifyOfPropertyChange(() =>

我试图解决这个问题。在WFP应用程序中,我将binadble集合绑定到listBox的属性ItemSource

财产签名为:

    public BindableCollection<UserInfo> Friends
    {
        get { return _friends; }
        set
        {
            _friends = value;
            NotifyOfPropertyChange(() => Friends);
        }
    }
publicbindablecollection好友
{
获取{return\u friends;}
设置
{
_朋友=价值;
财产变更通知(()=>朋友);
}
}
UserInfo类consit属性:

  • BitmapImage ProfilePhoto{get;set;}
  • 字符串Nick{get;set}
  • 字符串状态{get;set;}//脱机、联机、聊天
  • 字符串聊天室{get;set;}//用户聊天的聊天室的名称
我每10秒会得到一个新的数据,如IDictionary=>()

我需要刷新列表框中的数据。所以我试着这样做:

    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;

    }
private void RefreshContactsData(IEnumerable freshFriends)
{
//将所选项目存储在列表框中
var tempSelectedFriend=SelectedFriend;
//将选择索引存储在列表框中
var tempSelectedIndex=SelectedFriendsIndex;
//清除绑定在listBox ItemSource上的属性
朋友们;
foreach(freshFriends中的var freshFriend)
{
freshFriend.Value.IsFriend=true;
//添加新数据
添加(freshFriend.Value);
}
休息室();
//设置
SelectedFriend=临时SelectedFriend;
SelectedFriendsIndex=tempSelectedIndex;
}
问题是:

我将当前选定项存储在listBox中,清除listBox,添加新数据,并将选定项设置回listBox。 但用户看到滚动条被移动并向后移动,同时选中的项目也被刷新


如何删除此不需要的行为。

我认为问题在于您的
SelectedFriend
属性引用了一个引用,该引用在重新填充您的集合时不再存在。UserInfo上是否有唯一标识用户的属性?(
Nick
?)。您可以存储此选定值,然后在重新填充集合后,查找
SelectedFriend
,并将其设置为
Nick
与存储值匹配的项目

要防止列表框滚动条跳转,请不要删除然后从BindableCollection中添加回所有项

将RefreshContactsData重写为:

  • 删除好友中已存在但freshFriends中不再存在的项目
  • 添加freshFriends中存在但Friends中不存在的项目
  • 更新Friends和freshFriends中的现有项目

  • 您可能需要在UserInfo上实现INotifyPropertyChanged。

    No,SelectedFriedn存在于列表框中。问题导致我清除项目并添加新值。正如Zamboni提到的,一个更好的方法是通过更改单个项目来操作您已经拥有的BindableCollection。如果您不愿意将INotifyPropertyChanged添加到UserInfo模型中,那么可以创建一个实现INPC的包装器UserInfoViewModel,并将您的集合改为该类型。