Cleve Cleve - 9 months ago 119
C# Question

How can I reference the ListView DataContext from within the ListView.ItemTemplate in XAML?

I have a ListView whose DataContext is set to my ViewModel. The ListView.ItemsSource is set to a Collection Property of the ViewModel. There is a Property called MyIndex say on this ViewModel. The value of MyIndex changes during the execution of my project.

I need a way to access in XAML 'MyIndex' from within the ItemTemplate of the ListView so that I can change aspects of each ListViewItem based on the value of MyIndex.

I can't use TemplatedParent and then the .Parent property of the ListViewItem in the binding as .Parent isn't the ListView.

Here is some pseudo XAML to illustrate better what I mean.



<ListView ItemsSource="ItemsCollection">
<ListView.ItemTemplate>
<ItemContainerTemplate>
<Grid Background="{Binding <some xaml to reference MyIndex Property of ListView.DataContext to use in Converter>}">

</Grid>
</ItemContainerTemplate>
</ListView.ItemTemplate>
</ListView>





I'm not experienced with WPF so I hope this makes sense.

Many thanks in advance for any help.

Answer Source

This should do the trick. That way, you can use the DataContext of the parent in the children.

        <ListView ItemsSource="ItemsCollection">
        <ListView.ItemTemplate>
            <ItemContainerTemplate>
                <Grid Background="{Binding DataContext.MyIndex, RelativeSource={RelativeSource AncestorType=ListView}}">

                </Grid>
            </ItemContainerTemplate>
        </ListView.ItemTemplate>
    </ListView>