WPF List<T>增加、修改、删除后更新UI界面
  Fmh2GeNCglWw 2023年11月02日 51 0

      ObservableCollection首先它是一个集合,但它是一个既实现了INotifyPropertyChanged接口又实现了INotifyCollectionChanged接口的集合,这是它与List<T>的不同之处。

      使用ObservableCollection<T>注定要比List<T>消耗性能,所以我一直在探寻它们各自不同的使用场合。而且,当泛型参数T也实现了INotifyPropertyChanged接口时,就更加复杂了。

使用这个动态集合能很好的更新UI界面,但是它对LINQ的支持不友好,所以还是改用List<T>集合。

对象实体T实现接口INotifyPropertyChanged接口口,属性都要被监听,这样的当对象的属性改变,就会通知xaml界面刷新。另外viewmodel 也要实现的INotifyPropertyChanged,List<T>集合属性也设置监听。

例子:

public class HuBanModel : INotifyPropertyChanged{
        public event PropertyChangedEventHandler PropertyChanged;
        internal void NotifyPropertyChange(string propertyName)

        {

            if (PropertyChanged != null)
  PropertyChanged(this, new PropertyChangedEventArgs(propertyName));   } 
        private string _ceBanType;
        public string CeBanType
        {
            get { return _ceBanType; }
            set
            {
                _ceBanType = value;
                NotifyPropertyChange("CeBanType");
            }

        }
}

   

public class CeBanEditViewModel : INotifyPropertyChanged{
private List<HuBanModel> _leftHuBans;
        public List<HuBanModel> LeftHuBans

        {

            get { return _leftHuBans; }

            set

            {

                _leftHuBans = value;

                OnPropertyChanged("LeftHuBans");

            }

        }
}
public List<HuBanModel> RemoveList(List<HuBanModel> hubanList, int index)

        {

            List<HuBanModel> Newhubanlist = new List<HuBanModel>();

            hubanList.RemoveAt(index);

            int length = hubanList.Count;

            for (int i = 0; i < length; i++)

            {

                Newhubanlist.Add(hubanList[i]);

            }

            return Newhubanlist;

        }


        public void Remove(bool isleftCeBan, int index)

        {

            if (isleftCeBan)

            {


                this.LeftHuBans = RemoveList(this.LeftHuBans, index);

            }

            else

            {

                this.RightHuBans = RemoveList(this.RightHuBans, index);

            }

        }

   this.LeftHuBans = 要重新New 一个List对象,使引用地址发生改变,这样就能出发notif机制,通知UI更新界面。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  lh6O4DgR0ZQ8   2023年11月02日   54   0   0 javaListjson
  ZXL8ALkrtBPG   2023年11月02日   68   0   0 Listcpp
Fmh2GeNCglWw