【发布时间】:2014-01-27 10:09:00
【问题描述】:
编辑 2
在过去的几天里,我在尝试解决的一个问题上得到了一些帮助。在获得了多位用户的帮助后,我遇到了一个错误,我在周末一直在尝试修复,但仍然没有成功。
我创建了一个字典,我在其中传递了一个 string Country 和一个 ICollection 该国家/地区的 Places。
Dictionary<string, NewCountryClass> NTCD = new Dictionary<string, NewCountryClass>();
public void AddCountryCollection()
{
newCountryClass = new NewCountryClass(newCountry);
Collections.Add(newCountryClass);
NTCD.Add(newCountryClass.Country, newCountryClass);
}
public void AddPlace()
{
string Country = selectedItem.Country;
RenameQuestion(placeName);
NTCD[Country].Place.Add(placeName);
}
这是我的newCountryClass,我在其中存储了国家和该国家/地区的地点。
private ICollection<string> _places;
public ICollection<string> Places
{
get
{
return _places;
}
set
{
if (value == _places)
return;
_places = value;
RaisePropertyChanged(() => Places);
}
}
这是可以添加地点的地方,但我在添加 Country 阶段创建了我的类的实例,因此当时无法传递地点。 (编辑 - 我已将集合的初始化移到构造函数中,而不是按照建议移到 Places 属性中)。
public NewCountryClass(string country)
{
_places = new ObservableCollection<string>();
if (country != null)
{
_country = country;
}
}
因此,我尝试创建一个renamePlace() 方法:
public void RenamePlace(string place)
{
_places.Add(place);
}
然而,_places 似乎仍然为空,即使有此尝试。任何进一步的想法或我做错了什么?
【问题讨论】:
-
不应该在 NewCountryClass 构造函数中使用 Property Places 而不是字段 _places 吗?然后 _places 字段将被初始化。
-
@twrowsell 但是正如您在places 属性的
get部分中看到的那样,_places已经过验证并且仍然返回null。 -
只是为了澄清,在构造函数中它测试地方 != null 。我看不到所指的字段或变量。您有一个字段 _places 和一个属性 Places。应该是 _places 吗?
-
@twrowsell 看看我添加到 Sheridans 答案中的评论,这应该可以解释。
-
-1 用于更改您的代码,使当前的 cmets 和答案不再有意义。
标签: c# wpf class mvvm icollection