【问题标题】:Refresh data in ListBox - stop moving the scrollbar and flashed selected item刷新 ListBox 中的数据 - 停止移动滚动条并闪烁所选项目
【发布时间】:2011-06-22 05:43:52
【问题描述】:

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

属性签名是:

    public BindableCollection<UserInfo> Friends
    {
        get { return _friends; }
        set
        {
            _friends = value;
            NotifyOfPropertyChange(() => Friends);
        }
    }

UserInfo 类构成属性:

  • BitmapImage ProfilePhoto {get;set;}
  • 字符串尼克{get;set}
  • String Status{get;set;} //离线、在线、聊天
  • String ChatRoom{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;

    }

问题是:

我将当前选定的项目存储在列表框中,清除列表框,添加新数据,并将选定的项目设置回列表框中。 但是用户看到滚动条被移动并向后移动,并且选定的项目也闪烁了。

如何消除这种不受欢迎的行为。

【问题讨论】:

    标签: c# wpf listbox refresh scrollbar


    【解决方案1】:

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

    【讨论】:

    • 否,ListBox 中存在 SelectedFriedn。问题原因是我清除物品并增加新价值。我试试你的方法问题还是一样。
    • 正如 Zamboni 提到的,更好的方法是通过更改单个项目来操作您已经拥有的 BindableCollection。如果您对将 INotifyPropertyChanged 添加到您的 UserInfo 模型不满意,那么您可以创建一个实现 INPC 的包装器 UserInfoViewModel,并将您的集合改为该类型。
    【解决方案2】:

    为防止列表框滚动条跳跃,请不要删除,然后从 BindableCollection 重新添加所有项目。

    将 RefreshContactsData 重写为:

    1. 删除 Friends 中已存在但freshFriends 中不再存在的项目。
    2. 添加freshFriends 中存在但Friends 中不存在的项目。
    3. 更新 Friends 和 freshFriends 中的现有项目。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2017-01-17
      • 2011-09-06
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2015-10-18
      相关资源
      最近更新 更多