WPF ComboBox数据绑定到一个类

时间:2011-02-07 11:19:54

标签: c# wpf data-binding combobox

是否可以将WPF组合框绑定到类。我有一个实现IEmunerable和IEnumerator的类,并包含一个对象列表,如下所示:

class MyClass
{
    public string Title { get; set; }
    public string Directory { get; set; }

    public MyClass(string title, string directory)
    {
        Title = title;
        Directory = directory;
    }
}

class MyClasses : IEnumerable, IEnumerator
{
    private List<MyClass> allClasses;
    private int position = 0;

    public List<MyClass> GetClasses()
    {
        allClasses = new List<MyClass>()
        {
            new MyClass("example1", "dir1"),
            new MyClass("example2", "dir2")
        };

        return allClasses;
    }


    public IEnumerator GetEnumerator()
    {
        return (IEnumerator) this;
    }

    public object Current
    {
        get
        {
            return allClasses[position];
        }
    }

    public bool MoveNext()
    {
        position++;
        return (position < allClasses.Count());            
    }

    public void Reset()
    {
        position = -1;
    }
}

所以现在我想将它绑定到WPF组合框。这就是我所拥有的,它不起作用(我得到一个对象的类型名称列表):

        allClasses.GetClasses();

        cboTest.ItemsSource = allClasses;
        cboTitle.SelectedValue = "Title";

有谁能告诉我如何实现这种绑定?

2 个答案:

答案 0 :(得分:2)

cboTitle.SelectedValue = "Title";

应该是

cboTitle.DisplayMemberPath = "Title";

答案 1 :(得分:1)

更改

cboTitle.SelectedValue =“Title”;

cboTitle.DisplayMemberPath =“Title”;