Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ItemSource vs Datacontext in wpf

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

like image 888
Sauron Avatar asked May 15 '09 08:05

Sauron


People also ask

What is the difference between DataContext and ItemsSource?

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.

What is ItemsSource in WPF?

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.

What is the use of DataContext in WPF?

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.

What is DataContext?

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.


1 Answers

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.

like image 176
Martin Harris Avatar answered Sep 20 '22 13:09

Martin Harris