Thursday, August 26, 2010

Difference between DataContext and ItemsSource in WPF/Silverlight

In this post I will try to illustrate the difference between DataContext and ItemsSource property in Silverlight/WPF. These two properties don't serve the same purpose.
  1. DataContext expects an object type where ItemsSource expects IEnumerable type objects.
  2. DataContext is a dependency property is exposed by FrameworkElement base class,where as ItemsSource is defined by the ItemsControl class. All the descendants of FrameworkElement can utilize the DataContext property and set an object to its value. But we can only set a type of IEnumerable(or instance of class that derives from).
     
  3. 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.
     
  4. DataContext is mainly used to hold common data that other child want to share. Thus it can be inherited by other child elements without problem. But for ItemsSource, it not used to share data in the visual tree. It is only valid for the element that defined. There is still one thing to be noted is that the child element can override the DataContext of the perent DataContext no mater directly or indirectly.
Examples:

Suppose we have a Person Class which has a property Name. Now in Xaml we can say like:



See full details: http://www.c-sharpcorner.com/UploadFile/tirthacs/2101/Default.aspx