WPF可观察集合

时间:2015-11-26 10:16:52

标签: wpf observablecollection

我在视图模型中有一个ObservableCollection,它绑定到视图中的DataGrid,但是如果有人添加了新行或者有人修改了该行,则不会触发CollectionChanged事件已存在的行。

    public void onCollectionEventFired(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {

        }
        if (e.OldItems != null)
        { 

        }
    }


    #region Properties
    public ObservableCollection<Expenses> expenses
    {
        get
        {
            if (_expenses == null)
            {
                _expenses = new ObservableCollection<Expenses>();
                _expenses.CollectionChanged += onCollectionEventFired;
            }

            return _expenses;
        }
    }

1 个答案:

答案 0 :(得分:0)

您应该在ViewModel中订阅CollectionChanged个活动,而不是您的收藏夹。

public class MyVM
   {
      public MyVM()
      {
         this.expenses.CollectionChanged += onCollectionEventFired;
      }
   }

您需要set{}来为集合分配更改。

public ObservableCollection<Expenses> expenses
    {
        get
        {
            if (_expenses == null)
            {
                _expenses = new ObservableCollection<Expenses>();
            }

            return _expenses;
        }
        set
        {
            _expenses = value;
        }
    }