有人可以告诉我为什么我在尝试执行下面的添加时不断收到 NULL 引用异常吗?这仅ObservableCollection
在开始时为空时发生。如果从一开始就在集合中存在数据,则它可以正常工作。
加载ObservableCollection
和设置集合ViewSource
:
private void LoadCodeSets()
{
this.codeSetData = new ObservableCollection<CodeSet>();
var query = from c in context.CodeSets
where c.LogicallyDeleted == 0
orderby c.CodeSetID ascending
select c;
foreach (CodeSet c in query)
{
this.codeSetData.Add(c);
this.codeSetView = (ListCollectionView)CollectionViewSource.GetDefaultView(codeSetData);
this.codeSetRadGridView.ItemsSource = this.codeSetView;
}
}
将新记录添加到空数据网格
private void Add_CodeSet_Click(object sender, RoutedEventArgs e)
{
try
{
bool doesCodeSetExist = false;
if (codeSetView == null)
{
codeSetView.AddNewItem(new CodeSet());
}
else
{
foreach (CodeSet cs in codeSetView)
{
if (cs.CodeSetID == 0)
{
doesCodeSetExist = true;
this.lblMessages.Foreground = Brushes.Red;
this.lblMessages.FontWeight = System.Windows.FontWeights.ExtraBold;
this.lblMessages.Content = "Please fill in new user form and click Save User.";
this.lblMessages.Visibility = Visibility.Visible;
}
}
if (!doesCodeSetExist)
{
CodeSet newCodeSet = new CodeSet();
codeSetView.AddNewItem(newCodeSet);
}
}
}
catch (Exception ex)
{
Error.LogError(ex);
}
}