gpt4 book ai didi

mvvm - 在 MVVM 中将 ObservableCollection 绑定(bind)到数据网格

转载 作者:行者123 更新时间:2023-12-03 10:48:48 25 4
gpt4 key购买 nike

我是 XAML 的新手,我正在尝试将 ObservableCollection 绑定(bind)到 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" />

最佳答案

查看 NotifyCollectionChangedEventArgs class 上的文档.请注意,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());

关于mvvm - 在 MVVM 中将 ObservableCollection 绑定(bind)到数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com