DataGrid: Binding inside of DataGridTemplateColumn to property of the list

2.4k views Asked by At

A list is bound to a DataGrid in Silverligh 4:

<data:DataGrid
        x:Name="dataGrid"    
        ItemsSource="{Binding DetailsCollection}"
        IsReadOnly="True">
    <data:DataGrid.Columns>                    
        <data:DataGridTemplateColumn>
            <data:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding IsDirty, Converter={StaticResource IsDirtyConverter}}" HorizontalAlignment="Center" VerticalAlignment="Center" />
                </DataTemplate>
            </data:DataGridTemplateColumn.CellTemplate>
        </data:DataGridTemplateColumn>
    </data:DataGrid.Columns>
</data:DataGrid>

The IsDirty property bound to the TextBlock in the DataGridTemplateColumn is a property of the DetailsCollection. The Binding inside a DataGridTemplateColumn is looking at the properties of the specific item in a list. How could I change that behaviour to get to the property of the list?

1

There are 1 answers

0
Brian On BEST ANSWER

You can't do this "out of the box". The reason is that the DataContext of the DataGridCell is set to the item it is bound to. There are a few different ways to do this. The easiest way probably is just to modify your data item to refer back to the list. If you need to do this alot, you may want to code up a tool to help you.

You could create an attached property called something like AncestorDataContext that walks the display tree (see VisualTreeHelper) and searches for the target element by name. When it finds it, it sets the DataContext of it's FrameworkElement to the found control, your DataGrid. I've been using this approach a lot to make up for the lack of RelativeSource FindAncestor in SL.

<DataTemplate><Border custom:AncestorDataContext="dataGrid">
  <TextBlock Text="{Binding ItemsSource.IsDirty, Converter={StaticResource IsDirtyConverter}}"  HorizontalAlignment="Center" VerticalAlignment="Center" />