1

我用这个构造函数来初始化这个对象

 ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();

原来 allTabs 初始化后为空。因此,我无法向其中添加 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);
            }
        }
    }
}
4

5 回答 5

3

这里(在构造函数中MyHomeworkViewModel):

ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();

您创建了一个隐藏类成员的局部变量,因此在构造函数调用后它仍然为空。为了避免这种情况,只需跳过语句开头的类型:

allTabs = new ObservableCollection<MyHomeworkModel>();
于 2013-01-18T15:34:14.273 回答
1

如果你创建

ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();

在您的构造函数中,它将在用完后被删除。在外面声明它,然后调用

allTabs = new ObservableCollection<MyHomeworkModel>();
于 2013-01-18T15:33:23.237 回答
1
 public MyHomeworkViewModel()
    {
        allTabs = new ObservableCollection<MyHomeworkModel>();
        selectedTab = new MyHomeworkModel();
        AddCourseCommand = new AddCourseCommand(this);
    }
于 2013-01-18T15:33:40.287 回答
0

该行ObservableCollection<MyHomeworkModel> allTabs = new ObservableCollection<MyHomeworkModel>();没有allTabs 字段设置为新集合,而是创建新的局部变量并将该局部变量设置为新集合。要初始化该字段,您应该将该行更改为:

allTabs = new ObservableCollection<MyHomeworkModel>();
于 2013-01-18T15:33:28.190 回答
0

这是 C# 约定在私有类变量前加上下划线的原因之一:

private ObservableCollection<MyHomeworkModel> _allTabs;

更多指南:http: //msdn.microsoft.com/en-gb/library/vstudio/ms229042%28v=vs.100%29.aspx

于 2013-01-18T15:59:09.927 回答