title: Get Checkbox value in Datagrid bound to an ItemsSource in wpf
body: <p>In WPF, I created a Datagrid that is bound to an ItemsSource and then I added another column which is not bound to the itemssource. I'm trying to iterate over rows in Datagrid and get the checkbox value(true or false). Here is a snippet from my Datagrid:</p>
  
  <pre><code>&lt;DataGridTemplateColumn x:Name="CheckBoxColumn" Width="Auto"&gt;
      &lt;DataGridTemplateColumn.Header&gt;
          &lt;CheckBox Content="Select All" Style="{StaticResource StdCheckBoxStyle}" x:Name="headerCheckBox"/&gt;
      &lt;/DataGridTemplateColumn.Header&gt;
      &lt;DataGridTemplateColumn.CellTemplate&gt;
          &lt;DataTemplate&gt;
              &lt;CheckBox x:Name="checkBoxRow" Margin="45 2 0 0" Style="{StaticResource StdCheckBoxStyle}"
                              IsChecked="{Binding IsChecked, ElementName=headerCheckBox, 
                                          Mode=OneWay}" /&gt;
          &lt;/DataTemplate&gt;
      &lt;/DataGridTemplateColumn.CellTemplate&gt;
  &lt;/DataGridTemplateColumn&gt;
  &lt;DataGridTextColumn Binding="{Binding Index, Mode=OneWay}" IsReadOnly="True" Width="Auto" Header="Index"/&gt;
  </code></pre>
  
  <p>Datagrid is bound to an ItemsSource, which is an ICollection of MyObject. Here is what I did in code behind:</p>
  
  <pre><code>    public IEnumerable&lt;DataGridRow&gt; GetDataGridRows(DataGrid grid)
      {
          var itemsSource = grid.ItemsSource as IEnumerable;
          if (null == itemsSource) yield return null;
          foreach (var item in itemsSource)
          {
              var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
              if (null != row) yield return row;
          }
      }
  
      private void OnUpdate(object obj)
      {
        var rows= GetDataGridRows(MyDatagrid); 
  
          foreach (DataGridRow r in rows)  
          {  
              DataRowView rv = (DataRowView)r.Item;
              foreach (DataGridColumn column in MyDatagrid.Columns)
              {
                  if (column.GetCellContent(r) is CheckBox)
                  {
                      CheckBox cellContent = column.GetCellContent(r) as CheckBox;
                   //do something
                  }
              }
          } 
  
      }
  </code></pre>
  
  <p>But after running this piece of code, I get an exception:</p>
  
  <pre><code>Unable to cast object of type '...MyObject' to type 'System.Data.DatarowView'.
  </code></pre>
  
  <p>I looked a little bit and found out that in MSDN:</p>
  
  <pre><code>the DataItem property of the GridViewRow "Gets the underlying data object to which the GridViewRow object is bound."
  </code></pre>
  
  <p>I know the problem, I know the reason but couldn't find a way to fix it. Thanks for your attention.</p>