2
votes

my problem is that I want to set the selectedItem (mark a row in a datagrid). I've searched a lot and actually I hope there is a better solution instead of iterate through the datagrid.

my suggestion:

I have a Number with the value 3 and I want that the datagrid-row with the number 3 is marked.. I tried this one:

DataGridRow row = (DataGridRow)gridErrors.ItemContainerGenerator.ContainerFromItem(gridErrors.SelectedItem);

        if (row != null)
        {
            ErrorInfo info = row.Item as ErrorInfo;

            var blubb = from c in this.objectsToSync
                        where c.Number == info.Number
                        select c;

            if (blubb != null)
            {
                gridCsvContent.SelectedItem = blubb;
                gridCsvContent.ScrollIntoView(blubb);
                DataGridRow rowContent = (DataGridRow)gridCsvContent.ItemContainerGenerator.ContainerFromItem(gridCsvContent.SelectedItem);
                rowContent.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }    

First I extract the DataGridRow where my Number is from (value 3) then I havea linq query where I get the object with the number 3. Then I want to set the selectedItem but it's null afterwards.

Is there a solution where I not have to iterate through the datagrid..? Is there a way to set the selected item directly?

Thank you very much in advance! kr

1

1 Answers

1
votes

Unfortunately you will have to iterate over the collection to match to existing data in a cell.

If you're using the MVVM pattern you could move this logic to the ViewModel and work on the underlying data directly. You can create a dependency property to bind the SelectedItem to. I think you'll still need an event in the code behind to call ScrollIntoView though.