[英]How to add elements to IList collection using a function
我只是想了解 WPF treeview 的示例。
我的目标是用一些存储在列表中的项目填充 treeview。
这是一个例子:
public class Person
{
readonly List<Person> _children = new List<Person>();
public IList<Person> Children
{
get { return _children; }
}
public string Name { get; set; }
}
//Some added nodes:
public static Person GetFamilyTree()
{
// In a real app this method would access a database.
return new Person
{
Name = "David Weatherbeam",
Children =
{
new Person
{
Name="Alberto Weatherbeam",
Children=
{
new Person
{
Name="Zena Hairmonger",
Children=
{
new Person
{
Name="Sarah Applifunk",
}
}
},
new Person
{
Name="Jenny van Machoqueen",
Children=
{
new Person
{
Name="Nick van Machoqueen",
},
new Person
{
Name="Matilda Porcupinicus",
},
new Person
{
Name="Bronco van Machoqueen",
}
}
}
}
}
}
};
}
到目前为止它有效。
现在我想用我之前创建的列表替换第一个父节点下的 static 人员,读取文件。
XDocument ecad = XDocument.Load(openFileDialog.FileName);
GlobalVar.persons = new List<Persons>(); //globally available list
Person person = null;
//Einlesen der XML-Datei in lokale Variable (Model)
foreach(XElement elem in ecad.Descendants("Variable"))
{
if (elem.Element("Name") != null)
{
person = new Person(){ Name = elem.Element("Name").Value };
persons.Add(person);
}
}
现在我想将这些 Persons 添加到 root-person
//GlobalVar.List<Persons> persons
public static Person GetFamilyTree()
{
return new Person{
Name = "Family",
Children = persons
}
}
那么如何用从文件中读取数据的 function 替换Children = new...
?
我真的很困惑
我认为令人困惑的是,
Children
是一个只读属性,但使用“静态 Children”它可以工作,而 IList 则不能(因为 readonly)。 有人可以解释一下区别吗?
您的GetFamilyTree()
方法使用嵌套的 object 初始化程序。 请在此处参考 Jon Skeet 的回答以获取更多信息。
如果您打算从某个源读取数据然后设置Children
属性,则应向其添加 setter。 您还可以删除支持字段:
public class Person
{
public IList<Person> Children { get; set; } = new List<Person>();
public string Name { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.