Datagrid.ItemContainerGenerator not started / ContainerFromItem is always null

Dec 10, 2009 at 7:37 PM

Dear all,

I struggle with programmatically changing the background color of rows in a datagrid. The basic approach is clear - use Datagrid.ItemContainerGenerator.ContainerFromItem() to obtain the DataGridRow (the container) for which to set the background brush.

However, ItemContainerGenerator.ContainerFromItem() always returns null, and ItemContainerGenerator.Status stays at "NotStarted", independent on the visual state of the data grid.

BTW - the grid is nicely displayed, and changing the background e.g., after selecting a row or after cell loading works without problems.


private void UpdateRowBackgroundFromItemStates()


  IEnumerable items = this.dataGrid.ItemsSource;

  foreach (object item in items) 
     ItemState state = item as ItemState; // ItemState contains the data to be displayed
  if (state != null)
        // This is always NotStarted
        GeneratorStatus status = this.dataGrid.ItemContainerGenerator.Status;

        // This always returns null. Note - ContainerFromIndex does not work, either
        DependencyObject obj = this.dataGrid.ItemContainerGenerator.ContainerFromItem(state);

        // code removed ...



<dg:DataGrid x:Name="dataGrid" RowHeight="28" FontSize="12" DockPanel.Dock="Bottom" ColumnHeaderStyle="{StaticResource colHeaderStyle}" Style="{StaticResource dg_Style}" Margin="10,0,10,0" CellStyle="{StaticResource cellStyle}">

 <dg:DataGridTemplateColumn x:Name="NameColumn" Header="" >
<ctl:Label LocalizedTextFullName="{Binding Path=Description}" Loaded="labelCellLoaded" /> 
<!-- more items removed -->

I appreciate any ideas.



Dec 10, 2009 at 9:20 PM

Got it - the first call to the method took place before the main window was completely loaded.