将ObservableCollection绑定到MVVM中的datagrid

时间:2013-02-14 14:21:26

标签: mvvm binding datagrid observablecollection

我是XAML的新手,我正在尝试将ObservableCollection绑定到MVVM中的datagrid。 我想在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"  />

1 个答案:

答案 0 :(得分:0)

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

因此,如果对ObservableCollection执行Add操作,则OldItems为null(且有效)。只需在代码中执行检查,例如:

            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());