2

I'm new to WPF programming and I have this question going through my mind.

Why does binding only work when using properties instead of fields?

Here's the example that gave me this question:

xaml:

<ListBox ItemsSource="{Binding requiredPermissions}" DisplayMemberPath="MyText" Grid.Row="1" ></ListBox>

code behind(works):

public ObservableCollection<MyNotifyableText> requiredPermissions { get; set; }

code behind (doesn't work):

public ObservableCollection<MyNotifyableText> requiredPermissions; 

Thanks in advance.

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Mu'men Tayyem
  • 173
  • 3
  • 8

2 Answers2

9

Why does binding work when using properties instead of fields?

Because Microsoft use reflection behind the scenes to resolve the binding paths at runtime, and they only search for public properties of the DataContext using the Type.GetProperty method.

So you can only bind to public properties - not fields.

mm8
  • 163,881
  • 10
  • 57
  • 88
1

It seems that you aren't binding to the property correctly. The Binding isn't smart enough to know where is your property defined. You should set the DataContext of the View first with DataContext=...

Try this:

Put a name to your view and set itself to be the data context:

<Window x:Name="MyWindow" DataContext="{Binding ElementName=MyWindow}" ... />

Then, your ListBox Binding should work.

SuperJMN
  • 13,110
  • 16
  • 86
  • 185