Binding Previous Item's data in ItemsControl

For a data-bound ItemsControl, each item in the source collection is the DataContext for
the generated UI container. 
By default, the binding expressions used in the ItemTemplate are evaluated with respect to this DataContext. 
This is useful if all of the information that the template needs is contained in this context. This is actually the case in the vast majority of data binding expressions. 
However, there might be times when you also want to take a peek at the previous item to do some work. 
For example, say you are plotting a sales chart and you want to show the percentage change in market share over five years.
Here the change can be calculated within the ItemTemplate and shown in red for a
decrease and in green for an increase. In this case, it is necessary to have information
about the previous item in the data-bound list. 
This is where the exact scenario that the RelativeSource class was designed for with its PreviousData property. RelativeSource.PreviousData points to the previous item in the bound collection and can be used by setting the binding’s RelativeSource property. Once the relative source property is set, it is considered the source for the binding expression.

<Binding Path=”.” RelativeSource=”{RelativeSource PreviousData}” />

Comments

Popular posts from this blog

How UI Layout Works

From XAML to Xamarin