views:

34

answers:

2

I am trying to implement reordering rows in a Silverlight DataGrid. For this I am extending the default DataGridDragDropTarget, and I need to override and implement the following method:

protected override DataGridRow ContainerFromIndex(DataGrid itemsControl, int index)
{

}

How can I get the DataGridRow from the DataGrid and the Index?

+1  A: 

I haven't looked at the DataGridDragDropTarget yet, but couldn't you do just

protected override DataGridRow ContainerFromIndex(DataGrid itemsControl, int index)
{
    var row = base.ContainerFromIndex(itemsControl, index);
    if (row != null)
    {
        // do something with row
    }
}

?

If that is not implemented for whatever reason, you can try this:

// requires Assembly System.Windows.Controls.Toolkit.dll

using System.Windows.Controls.Primitives;
// ...

protected override DataGridRow ContainerFromIndex(DataGrid itemsControl, int index)
{
    var rowsPresenter =
        itemsControl.GetVisualDescendants()
            .OfType<DataGridRowsPresenter>().FirstOrDefault();
    if (rowsPresenter != null)
    {
        var row = rowsPresenter.Children[index];
        // do something with row
    }
}

I don't know however how you want to implement the reordering of rows. Chances are you must keep track of your indexes by yourself and return one of your own stored index values in that method.

herzmeister der welten
This method is not implemented in the base class (simply returns null). Your implementation won't always work because the items might not visually appear in the same order than they are stored in the Children collection, ie. the index in Children can be different than the index of the row in the DataGrid. This happens when the data source has been changed after the rows have been rendered or because of the virtualization in the panel. However it did put me on the right track, so thanks for that. The rows expose the GetIndex() method that can be used to select the right one.
Xavier Poinas
+1  A: 

A slight improvement on Herzmeister's answer, see comments:

protected override DataGridRow ContainerFromIndex(DataGrid itemsControl, int index)
{
    var rowsPresenter = itemsControl.GetVisualDescendants().OfType<DataGridRowsPresenter>().FirstOrDefault();
    if (rowsPresenter != null)
    {
        return rowsPresenter.Children.OfType<DataGridRow>()
                .Where(row => row.GetIndex() == index).SingleOrDefault();
    }
    return null;
}
Xavier Poinas