0

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?

Vitalij
  • 4,587
  • 9
  • 42
  • 65

2 Answers2

2

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.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • But what shall I do if the class library uses Fields instead of properties? How do I bind to those then? – Vitalij Nov 22 '10 at 12:05
  • 1
    You can't bind to fields. You could write a wrapper class that takes an instance of the library class and exposes its fields as properties. – Botz3000 Nov 22 '10 at 12:07
  • And to get notification mechanism in my wrapper class do I have to check for changes in the library every n seconds and then rise PropertyCnaged event? – Vitalij Nov 23 '10 at 12:14
  • Yes, that's a possibility, if you expect the value to change over time. – Botz3000 Nov 23 '10 at 12:17
1

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.

Femaref
  • 60,705
  • 7
  • 138
  • 176
  • Thanks, I know that it is not a good practise to use fields, I used fields only to test the binding, but then I realised that WPF can't use fields. – Vitalij Nov 22 '10 at 12:02