Vitalij
Vitalij

Reputation: 4625

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?

Upvotes: 0

Views: 123

Answers (2)

Botz3000
Botz3000

Reputation: 39620

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.

Upvotes: 2

Femaref
Femaref

Reputation: 61467

The second code doesn't contain standard properties, it contains fields. WPF needs properties, also you should implement INotifyPropertyChanged, otherwise wpf won't catch changed data.

On another note: don't expose fields directly, encapsulate them in properties. Doing that, you can control the data getting into the class, also code outside the class itself can't influence the class in non-wanted ways.

Upvotes: 1

Related Questions