简体   繁体   中英

WPF ComboBox Databound to a class

Should it be possible to bind a WPF combo box to a class. I have a class that implements IEmunerable and IEnumerator, and contains a list of objects, as follows:

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;
    }
}

So now I want to bind this to a WPF combobox. Here's what I have, which doesn't work (I instead get a list of type names of the objects):

        allClasses.GetClasses();

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

Can anyone tell me how to implement this binding?

cboTitle.SelectedValue = "Title";

应该

cboTitle.DisplayMemberPath = "Title";

Change

cboTitle.SelectedValue = "Title";

to

cboTitle.DisplayMemberPath = "Title";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM