我正在尝试从这个网站学习如何做 http://msdn.microsoft.com/en-us/library/cc265158(v=vs.95).aspx但是代码不会编译,我会收到很多错误。
这是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bail
{
public class ListboxMenuItem
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
public ListboxMenuItem(String firstName, String lastName, String address)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
}
}
class ListboxMenuItems
{
List<ListboxMenuItem> Items;
Items = new List<ListboxMenuItem>();
Items.Add(new ListboxMenuItem("Michael", "Anderberg", "12 North Third Street, Apartment 45"));
Items.Add(new ListboxMenuItem("Chris", "Ashton", "34 West Fifth Street, Apartment 67"));
Items.Add(new ListboxMenuItem("Cassie", "Hicks", "56 East Seventh Street, Apartment 89"));
Items.Add(new ListboxMenuItem("Guido", "Pica", "78 South Ninth Street, Apartment 10"));
}
}
所有错误都与项目有关
例如Items = new List<ListboxMenuItem>();
产生错误
Error 1 Invalid token '=' in class, struct, or interface member declaration ListboxMenuItems.cs 26 15 Bail
最佳答案
起初我只是更正了错误,但是在看到链接后我发现旧的答案并没有真正帮助。
不过,您仍然可以在底部找到它。
新答案
我刚看了链接,看来你还是做错了事。
你需要你的类继承自ObservableCollection<T>
,而不是 List
字段/属性你应该使用基类的功能(它已经有 Add
方法):
class ListboxMenuItems : ObservableCollection<ListboxMenuItem>
{
public ListboxMenuItems ()
{
// 'Add' here means 'base.Add'
Add (new ListboxMenuItem ("Michael", "Anderberg", "12 North Third Street, Apartment 45"));
Add (new ListboxMenuItem ("Chris", "Ashton", "34 West Fifth Street, Apartment 67"));
Add (new ListboxMenuItem ("Cassie", "Hicks", "56 East Seventh Street, Apartment 89"));
Add (new ListboxMenuItem ("Guido", "Pica", "78 South Ninth Street, Apartment 10"));
}
}
所有这些都清楚地写在您提供的引用资料中,因此您在采用文档中的代码时应该更加小心。
旧答案
您已将初始化代码放在类声明中,通常是方法、字段和属性所在的位置。
初始化代码被放置在一个名为“constructor”的特殊方法中,它与类同名,没有返回类型,并且被放置在相应的类中: p>
class ListboxMenuItems
{
public List<ListboxMenuItem> Items { get; private set; }
public ListboxMenuItems ()
{
Items = new List<ListboxMenuItem> {
new ListboxMenuItem ("Michael", "Anderberg", "12 North Third Street, Apartment 45"),
new ListboxMenuItem ("Chris", "Ashton", "34 West Fifth Street, Apartment 67"),
new ListboxMenuItem ("Cassie", "Hicks", "56 East Seventh Street, Apartment 89"),
new ListboxMenuItem ("Guido", "Pica", "78 South Ninth Street, Apartment 10")
};
}
}
我改变了Items
从一个领域到一个属性。这是一种更好的做法,因为您可以指定谁可以更改它(在我们的例子中,private set
只允许在 ListboxMenuItems
中设置它)。
我还使用了列表初始化器语法,允许您删除许多 Add
呼吁采用更简洁、整洁的语法。
关于c# - 尝试使用 WPF 创建一个 ListBox,我想通过代码填充成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6335331/