Datagrid.ItemContainerGenerator not started / ContainerFromItem is always null

Dec 10, 2009 at 6: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 ...
     }
   }
 }
}

 

XAML:

<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:DataGrid.Columns> 
 <dg:DataGridTemplateColumn x:Name="NameColumn" Header="" >
 
<dg:DataGridTemplateColumn.CellTemplate>
 
<DataTemplate>
  
<Label>
    
<ctl:Label LocalizedTextFullName="{Binding Path=Description}" Loaded="labelCellLoaded" /> 
  </Label>
<!-- more items removed -->
</
DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
</dg:DataGrid.Columns> 
</dg:DataGrid> 

I appreciate any ideas.

Regards

 Michael

Dec 10, 2009 at 8:20 PM

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

Regards

 Michael