-1

How to get all DataGridRows in DataGrid? like

foreach (DataGridRow dr in postQueue.Items)
    {
        Console.WriteLine(dr.GetIndex());
    }

of cource wrong, because i need every DataGridRow element, not struct.

for (int i = 0; i < postQueue.Items.Count; i++)
            {
                DataGridRow row = (DataGridRow)postQueue.ItemContainerGenerator
                                                           .ContainerFromIndex(i);
                row.Header = i.ToString();
            }

Throws row was null

Apepenkov
  • 415
  • 1
  • 3
  • 10
  • 2
    Possible duplicate of [Get datagrid rows](https://stackoverflow.com/questions/12762310/get-datagrid-rows) – Jonas Sep 12 '19 at 09:02
  • There are no `DataGridRow` containers for items that are not currently visible due to the UI virtualization that the `DataGrid` implements. You can turn this off but it comes with a performance penalty. Why do you need access to the containers? – mm8 Sep 12 '19 at 09:18
  • I wanted to add indexes automatically to the left side of datagrid – Apepenkov Sep 12 '19 at 09:29

1 Answers1

1

why don't you bind your DataGrid to an ObservableCollection?

XAML :

<DataGrid ItemsSource="{Binding Path=YourList}" >
...
</DataGrid>

MVVM :

private ObservableCollection<T> yourList = new ObservableCollection<Hole>();
public ObservableCollection<T> YourList
{
    get { return yourList; }
    set
    {
        this.yourList = value;
        NotifyPropertyChanged("YourList");
    }
}

then to get it just do :

foreach (T element in this.YourList)
{
   ...
}
Siegfried.V
  • 1,508
  • 1
  • 16
  • 34