1

我是 XAML 的新手,我正在尝试将 ObservableCollection 绑定到 MVVM 中的数据网格。我想在 CollectionChanged 时收到通知。但它抛出空异常。

当我出错时请告诉我。提前致谢。

以下是 viewModel 背后的代码:

public class MainwindowViewModel : INotifyPropertyChanged
{
    MyObject myObj;
    ObservableCollection<MyObject> _ocObj;

    public MainwindowViewModel()
    {
        _ocObj = new ObservableCollection<MyObject>();
        myObj = new MyObject();
        myObj.ID = 0;
        myObj.Name = "Name";
        _ocObj.Add(myObj);
        _ocObj.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_ocMyobj_CollectionChanged);
    }

    void _ocMyobj_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        System.Windows.MessageBox.Show("propeties changed @ " + e.NewStartingIndex.ToString()
            + " old items starting @ " + e.OldStartingIndex + " olditems count " + e.OldItems.Count.ToString()
            + " action " + e.Action.ToString());
    }


    public ObservableCollection<MyObject> ocObj
    {
        get { return _ocObj; }
        set
        {
            PropertyChanged(this, new PropertyChangedEventArgs("ocMyobj"));
        } 
    }

    public string Name
    {
        get { return myObj.Name; }
        set
        {
            if (value !=null)
            {
                myObj.Name = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }

    public int ID
    {
        get { return myObj.ID; }
        set
        {
            if (myObj.ID != value)
            {
                myObj.ID = value;
                PropertyChanged(this, new PropertyChangedEventArgs("ID"));
            }
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

public class MyObject
{
    public string Name { get; set; }
    public int ID { get; set; }
}

下面是 XAML:

<Window.Resources>
    <vm:MainwindowViewModel x:Key="someObj"/>
</Window.Resources>
<DataGrid ItemsSource="{Binding ocObj}" DataContext="{Binding Source={StaticResource someObj}}" AutoGenerateColumns="True"  />
4

1 回答 1

0

查看NotifyCollectionChangedEventArgs 类的文档。请注意,OldItems 对象仅“获取受替换、删除或移动操作影响的项目列表”。这意味着对于其他操作,OldItems 将为空。

因此,如果对您的 ObservableCollection 执行添加操作,则 OldItems 为空(且有效)。只需在您的代码中对其进行检查,例如:

            System.Windows.MessageBox.Show("propeties changed @ " + e.NewStartingIndex.ToString()
                + " old items starting @ " + e.OldStartingIndex + " olditems count " + 
                (e.OldItems == null ? "0" : e.OldItems.Count.ToString())
                + " action " + e.Action.ToString());
于 2013-02-14T21:56:47.207 回答