【发布时间】:2017-09-17 07:29:56
【问题描述】:
我是 MVVM 的新手,我有一个 Model.cs,其中包含一些“ID”和“PositionName”属性,我得到了 View.cs,其中包含 DataGrid,SelectedItems={Binding Items} 和 ItemSource={ Binding Position} 和一个带有 Command={Binding SHowEdits} 的按钮,点击后我在 'Items.PositionName == null' 处遇到了 NullReference 错误。
这是我的代码。
ViewModel.cs
class PositionVM : INotifyPropertyChanged
{
private ObservableCollection<PositionModel> _position;
private PositionModel _items;
private ICommand _showedits;
public ObservableCollection<PositionModel> Position
{
get
{
return _position;
}
set
{
_position = value;
NotifyProperty("Position");
}
}
public PositionModel Items
{
get
{
return _items;
}
set
{
_items = value;
NotifyProperty("Items");
}
}
public ICommand ShowEdits
{
get
{
if (_showedits == null)
_showedits = new ShowEdit();
return _showedits;
}
set
{
_showedits = value;
}
}
public PositionVM()
{
Position = new ObservableCollection<PositionModel>();
Position.Add(new PositionModel()
{
ID = 1,
PositionName = "asd"
});
}
public void ShowEditDialog()
{
if (Items.PositionName == null)
{
MessageBox.Show("ERROR");
}
else
{
PositionView view = new PositionView();
Data.ID = view.txtid.Text;
var z = new PositionView();
z.ShowDialog();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyProperty(String info)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
为什么会出现这个错误?我该如何避免呢?谢谢
【问题讨论】: