尝试使用WPF创建ListBox,我想通过Code填充成员

Coc*_*Dev 1 c# list visual-studio-2010 c#-4.0

我正在努力学习如何从这个网站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"));

    }
}
Run Code Online (Sandbox Code Playgroud)

所有错误都与Items有关

例如,Items = new List<ListboxMenuItem>();产生错误

错误1类,结构或接口成员声明中的标记'='无效ListboxMenuItems.cs 26 15保释

Dan*_*mov 5

起初我只纠正了错误,但是在看到链接之后我注意到旧答案并没有真正帮助.
你仍然可以在底部找到它.

新答案

我刚看了一下这个链接,看起来好像你做错了.
您需要继承自的类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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

所有这些都清楚地写在您提供的参考文献中,因此您应该更加谨慎地采用文档中的代码.

旧答案

您已将初始化代码放在类声明中,通常放置方法,字段和属性.

初始化代码放在一个名为"constructor"的特殊方法中,该方法与类同名,没有返回类型,并放在相应的类中:

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")
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

Items从一个领域变成了一个财产.这是一种更好的做法,因为您可以指定谁可以更改它(在我们的例子中,private set允许仅从内部设置ListboxMenuItems).

我还使用了list initializer语法,它允许你删除许多Add调用,转而采用更清晰,更无杂乱的语法.