5

Duplicate of :

Why are DataContext and ItemsSource not redundant?


In WPF we can assign list of item to ComboBox in 2 ways

//CODE #1
//WPF
<ComboBox name="cmbItems" ItemSource={Binding} />

//C#
cmbItems.DataContext = someList;

another way, directly assign itemsource

//CODE #2
//WPF
<ComboBox name="cmbItems" ItemSource={Binding} />
//C#
cmbItems. ItemSource = someList;

both serves the purpose, but whats the difference in above snippet? and which is good to use?

Community
  • 1
  • 1
Prashant Cholachagudda
  • 13,012
  • 23
  • 97
  • 162
  • possible duplicate of [Who has the best answer for why DataContext and ItemsSource are not redundant?](http://stackoverflow.com/questions/793340/who-has-the-best-answer-for-why-datacontext-and-itemssource-are-not-redundant) –  Sep 27 '11 at 16:47

2 Answers2

9

DataContext is mostly used on forms, controls etc.

An ItemSource is a relative path to do databinding on that DataContext.

For example when you make a form to edit Person details, then the DataContext would be Person and the different controls on the form will each bind on a seperate property on that object, for example Name, Date of Birth, etc.

Gerrie Schenck
  • 22,148
  • 20
  • 68
  • 95
2

In the second example you can leave out the ItemsSource={Binding}.. You are setting the ItemsSource directly to a value in your code behind.. You won't need a binding here. In your first example, you set the DataContext, and use a binding to retrieve it again from the DataContext..

But it doesn't really matter.. for both methods work fine...

I use the following thumb of rule: set it in code behind, if I have the collection available.. Set it in some kind of binding mode, if I need to transform the collection, so that I can use a IValueConverter to do the job...

Arcturus
  • 26,677
  • 10
  • 92
  • 107