wpfxamlbindingdatatemplatedataitem

Get DataItem in DataTemplate


Is there a way to get the actual DataItem of a DataTemplate. More specifically, I have a custom button which I use in a datatemplate:

<DataTemplate x:Key="SampleDataTemplate1">
    <custom:SampleButton />
</DataTemplate>

I use this in a listview to bind to a collection. I would like to pass a reference to the actual DataItem that is being bound. Something like this:

<DataTemplate x:Key="SampleDataTemplate1">
    <custom:SampleButton BoundItem="{Binding DataItem}" />
</DataTemplate>

Is this possible? How can this be accomplished?


Solution

  • You can bind to the data being used in data template. Here is an example:

    <DataTemplate x:Key="SampleDataTemplate1">
         <custom:SampleButton BoundItem="{Binding}" />
    </DataTemplate> 
    

    More details here (see Specifying the Path to the Value section):

    http://msdn.microsoft.com/en-us/library/ms752347.aspx#creating_a_binding

    The idea is that inside the data template all elements in their DataContext reference the item to which data template is bind to. And {Binding} construct without Path simply binds to the DataContext.