3

Why does public string name {get; set;} work when binding, but public string name; does not? Why is the getter required when they both return the same string?

bwoogie
  • 4,339
  • 12
  • 39
  • 72

1 Answers1

12

Because you can only bind to public properties in WPF. The following is a field and not a property:

public string name;

The binding engine only looks for properties when the binding expressions are evaluated using reflection at runtime.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • I believe the answer relates to the fact that one is a field and the other is a property with getters and setters. WPF likely only supports binding on properties to allow for user defined functionality in both the get and set. – Grace Atwood Mar 14 '17 at 19:09
  • 6
    @DanielAtwood That's exactly what mm8 said. – Dispersia Mar 14 '17 at 19:10
  • 1
    @DanielAtwood The first one is a property and the second one is a *field* and you can only bind to *properties* as I stated in the answer. – mm8 Mar 14 '17 at 19:11
  • @Dispersia I apologize. It appears his or her answer changed after posting that. – Grace Atwood Mar 14 '17 at 19:12
  • @mm8. I know that fact. But why the binding engine only looks for properties. Is there .net source code proving that? – Bigeyes Mar 14 '17 at 19:15
  • @Bigeyes http://stackoverflow.com/questions/842575/why-does-wpf-support-binding-to-properties-of-an-object-but-not-fields – Dispersia Mar 14 '17 at 19:19