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

在定义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");
                }

            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

话与山鬼听

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值