WPF中关于ListBox绑定数据的问题

来源:互联网 发布:淘宝刷销量排名靠后 编辑:程序博客网 时间:2024/06/05 06:44

在定义ListBox的ItemSource绑定时,出现了初次绑定有数据,但是数据变化时视图没有更新的情况。
错误发生时代码如下:

//尝试一private void binding(){    List<string> m_allpaths = new List<string>();    System.Windows.Data.Binding newBinding = new System.Windows.Data.Binding();    newBinding.Source = m_allpaths;    lsb1.SetBinding(System.Windows.Controls.ListBox.ItemsSourceProperty,newBinding);       }//尝试二,定义了一个类,此类中有个字段getAllPath为List<string>类型     public class AllPaths : INotifyPropertyChanged    {        public event PropertyChangedEventHandler PropertyChanged;        private ObservableCollection<string> m_allpaths = new ObservableCollection<string>();        public ObservableCollection<string> getAllPaths        {            get { return m_allpaths; }            set            {                m_allpaths = value;                if (PropertyChanged != null)                {                    this.PropertyChanged.Invoke(this,new PropertyChangedEventArgs("getAllPaths"));                }            }        }    }private void binding(){    AllPath m_allpaths = new AllPath();    System.Windows.Data.Binding newBinding = new System.Windows.Data.Binding();    newBinding.Source = m_allpaths;    newBinding.Path = new PropertyPath("getAllPaths");    lsb1.SetBinding(System.Windows.Controls.ListBox.ItemsSourceProperty,newBinding); }     

发现尝试一中的m_allpaths和尝试二中的getAllPath进行添加时,ListBox的视图均为刷新。百度之后,了解到一个问题,就是对于List< T >这类泛型,视图层是不能够获取到其数据更新的。在comobox和listbox等空间中,其item都是多组字符,因此需要用到以下ObservableCollection< T >,msdn中有对ObservableCollection的介绍:http://msdn.microsoft.com/zh-cn/magazine/dd252944.aspx。
只要将尝试二中的List< string >改成ObservableCollection< string >,即可绑定,也可以参照下面的代码:

private ObservableCollection<T> _default = new ObservableCollection<T>();        public ObservableCollection<CardViewModel> DeafultPro        {            get { return _default; }            set            {                if (_default != value)                {                    _default = value;                    RaisePropertyChanged("DeafultPro");                }            }        }
0 0
原创粉丝点击