Difference between Datacontext and ItemSource in WPF

Duplicate:

Why are DataContext and ItemsSource not redundant?


In WPF, we can assign a list of items to a ComboBox in two ways.

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

another way is to directly assign itemsource

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

both serve the purpose, but what is the difference in the above fragment? and what is useful to use?

+5
source share
2 answers

DataContext is mainly used for forms, controls, etc.

ItemSource is a relative path to bind data to this DataContext.

For example, when you create a form for editing Person data, then the DataContext will be Person, and various controls on the form will be attached to a separate property on this object, for example, Name, Date of Birth, etc.

+9
source

In the second example, you can leave the ItemsSource = {Binding} element. You directly set the ItemsSource to your code. You do not need a binding here. In the first example, you set the DataContext and use the binding to get it again from the DataContext.

But that doesn’t matter .. for both methods works fine ...

I use the following rule pointer: set it to the code behind if I have a collection available. Set it in some kind of binding mode if I need to convert the collection so that I can use IValueConverter to do this work ...

+2
source

All Articles