ItemSource vs Datacontext in wpf

Sauron picture Sauron · May 15, 2009 · Viewed 9.6k times · Source

Can any one give me the difference between Itemsource and DataContext of Listview in WPF? With example

Answer

Martin Harris picture Martin Harris · May 15, 2009

The item source (which must impliment IEnumerable) will be used to create the list of items that appears inside the list. The DataContext (which can be any object) is the default object to bind against for any bindings that you have specified for other properties on the ListView.

public List<string> ItemsObject = new List<string>() { "Item1", "Item2", "Item3" };
public AnyObject DataContextObject = new AnyObject() { WidthValue = 23 }

<ListView
           ItemsSource="{Resource_of_ItemsObject}"
           DataContext="{Resource_of_DataContextObject}"
           Width="{Binding Path=WidthValue}"/>

Will produce a list of "Item1", Item2", Item3" displayed with a width of 23.