gpt4 book ai didi

c# - 为什么observablecollection初始化为null?

转载 作者:太空宇宙 更新时间:2023-11-03 20:19:46 25 4
gpt4 key购买 nike

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

 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);
}
}
}
}

最佳答案

此处(在 MyHomeworkViewModel 的构造函数中):

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

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

allTabs = new ObservableCollection<MyHomeworkModel>();

关于c# - 为什么observablecollection初始化为null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14402133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com