【发布时间】:2013-06-04 20:38:38
【问题描述】:
我有一个带有命令的ViewModel (UserControlViewModel):
public Command PressMeCommand { get; set; }
还有:
#region Implementation of INotifyPropertyChanged
private File _myfile;
public File MyFile
{
get
{
return _myfile;
}
set
{
value = _myfile;
OnPropertyChanged("MyFile");
}
}
File 是我的类,其中有一个名为 read() 的方法。
我正在向我的allMyControls ObservableCollection<UserControlViewModel> 添加另一个命令,该命令绑定到我的主窗口中的按钮。以下代码来自 RootViewModel.cs
private void AddUserControl()
{
UserControlViewModel myNewControl = new UserControlViewModel();
myNewControl.PressMeCommand = new Command(() => OnUserControlPressed(myNewControl ));
allMyControls.Add(myNewControl );
}
最后我设置了新的命令:
private void OnUserControlPressed(UserControlViewModel item)
{
if (item != null)
{
item.MyFile.read();
Num = item.MyFile.channels.Count;
}
}
当我按下与 PressMeCommand 对应的按钮时,它给了我一个错误“NullReferenceException 未处理”。我的第一反应是,哦,我还没有初始化 MyFile,所以我转到了这个:
private void OnUserControlPressed(UserControlViewModel item)
{
if (item != null)
{
item.MyFile = new File();
item.MyFile.read(); //Here is the problem
Num = item.MyFile.channels.Count;
}
}
但问题仍然存在。现在我完全没有想法了。会是什么呢?如何正确初始化我的属性MyFile?
【问题讨论】:
-
你在哪里初始化
channels? -
哪一行抛出异常?
-
在 read() 方法中。
-
我已经编辑了这个问题,并在末尾附近添加了一条评论,显示了问题所在的行。
标签: c# wpf command nullreferenceexception