我使用此构造函数初始化此对象
ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();
事实证明,初始化后allTabs为null。由于这个原因,我无法将MyHomeworkModel对象添加到它。
请帮助我,并提前致谢。
using System.Windows.Input;
using System.Collections.ObjectModel;
using MyHomework;
namespace MyHomework__MVVM_
{
class MyHomeworkViewModel
{
private ObservableCollection<MyHomeworkModel> allTabs;
private MyHomeworkModel selectedTab;
public MyHomeworkViewModel()
{
ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();
selectedTab = new MyHomeworkModel();
AddCourseCommand = new AddCourseCommand(this);
}
public ObservableCollection<MyHomeworkModel> AllTabs
{
get
{
return allTabs;
}
set
{
allTabs = value;
}
}
public MyHomeworkModel SelectedTab
{
get
{
return selectedTab;
}
set
{
selectedTab = value;
}
}
public ICommand AddCourseCommand
{
get;
private set;
}
public void AddNewTab()
{
NewCourseName ncn = new NewCourseName();
ncn.ShowDialog();
if (ncn.courseName != null)
{
MyHomeworkModel newTab = new MyHomeworkModel();
newTab.Header = ncn.courseName;
AllTabs.Add(newTab);
}
}
}
}
答案 0 :(得分:3)
这里(在MyHomeworkViewModel
的构造函数中):
ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();
创建一个隐藏类成员的局部变量,因此在构造函数调用后它保持为null。为了避免这种情况,只需跳过语句开头的类型:
allTabs = new ObservableCollection<MyHomeworkModel>();
答案 1 :(得分:1)
如果你创建
ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();
在您的构造函数中,它将在用完后删除。在外面声明它并且只调用
allTabs = new ObservableCollection<MyHomeworkModel>();
答案 2 :(得分:1)
public MyHomeworkViewModel()
{
allTabs = new ObservableCollection<MyHomeworkModel>();
selectedTab = new MyHomeworkModel();
AddCourseCommand = new AddCourseCommand(this);
}
答案 3 :(得分:0)
第ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();
行不将allTabs
字段设置为新集合,它创建了一个新的本地变量,将该局部变量设置为新集合。要初始化字段,您应该将该行更改为:
allTabs = new ObservableCollection<MyHomeworkModel>();
答案 4 :(得分:0)
这是使用下划线为私有类变量添加前缀的C#约定的一个原因:
private ObservableCollection<MyHomeworkModel> _allTabs;
此处有更多指南: http://msdn.microsoft.com/en-gb/library/vstudio/ms229042%28v=vs.100%29.aspx