Can any one give me the difference between Itemsource and DataContext of Listview in WPF? With example
DataContext does not generate template, it only used to hold common data for other controls to bind. In terms of ItemsSource property, it is mainly used to generate template regardless of you set it in XAML or in the code behind. DataContext is mainly used to hold common data that other child want to share.
ItemsSource can be data bound to any sequence that implements the IEnumerable interface, although the type of collection used does determine the way in which the control is updated when items are added to or removed. When ItemsSource is set, the Items property cannot be used to control the displayed values.
Every FrameworkElement can be associated with a DataContext which will be used as the default data source during binding, if no other data source is specified in the binding code. Also, the children of this FrameworkElement auotmatically inherit this setting.
The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities and maintains an "identity cache" that guarantees that entities retrieved more than one time are represented by using the same object instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With