Question

I got the following:

<ListView ItemsSource="{Binding Path=Items}">                        
     <ListView.ItemTemplate>
         <DataTemplate>
             <TextBlock Text="{Binding Path=Name}" Foreground="{Binding Path=GridTextColor}"></TextBlock>
         </DataTemplate>
     </ListView.ItemTemplate>
</ListView>

The datacontext looks like this:

class{
 items = List with items (each row has a name property)
 GridTextColor = Brush
}

I bind the listview with all items. Each item contains a name and that name shows up nicely in the listview.

The problem is that i want all items inside the DataTemplate to have the Foreground set to the brush. With the code above that is not possible since when i am inside the DataTemplate i bind to the items that are sent in. Question, how can i bind to the "parent datacontext" to get the correct foreground color?

Was it helpful?

Solution

You can use RelativeSource in your binding to get parent's DataContext.

<TextBlock Text="{Binding Path=Name}"
           Foreground="{Binding Path=DataContext.GridTextColor,
                               RelativeSource={RelativeSource Mode=FindAncestor, 
                                                     AncestorType=ListView}}"/>

Or Set x:Name on ListView and bind using ElementName:

<ListView x:Name="myListView">
   ....
     <TextBlock Text="{Binding Path=Name}"
                Foreground="{Binding DataContext.GridTextColor,
                                     ElementName=myListView}" />
   ....
</ListView>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top