Search code examples
wpfbindingitemsource

Why DisplayMemeberPath doesn't accept a standard property?


I am binding a List of object to a ComboBox.

<ComboBox Name="comboPerson"  DisplayMemberPath="Name"/>

Where code behind looks like this:

List<Person> myFriends = new List<Person>()
{
    new Person("Jack", "Daniels", 8),
    new Person("Milla", "Jovovovich", 35),
    new Person("Umma", "Turman", 34)
};

comboPerson.ItemsSource = myFriends;

And if I use standart Properties, it doesn't display the name but, if the property is accessed via get accessors it is working. Here is what I mean:

Working version:

public string Name { get; set; }
public string Surnamge { get; set; }
public int Age { get; set; }

public Person(string name, string surname, int age)
{
    this.Name = name;
    this.Surnamge = surname;
    this.Age = age;
}

Non working version:

public string Name;
public string Surnamge;
public int Age;

public Person(string name, string surname, int age)
{
    this.Name = name;
    this.Surnamge = surname;
    this.Age = age;
}

The question is: why WPF is unable to get the value from a standard Property?


Solution

  • your "non working" version doesn't use Properties, it uses public Fields, which you usually should not use because it violates Encapsulation.

    WPF is designed so that it only accesses properties via their accessors. Fields are not accessed via accessors (which are generated by the compiler if you use the {get;set;} syntax), but directly. If you use properties, you can also take advantage of nice things like automatic updating (if you implement INotifyPropertyChanged properly).

    So, if you want to use Binding in WPF, you'll need to use properties.