Get Row from Index in Silverlight DataGrid

℡╲_俬逩灬. 提交于 2019-12-10 10:06:24

问题


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 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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/3993393/get-row-from-index-in-silverlight-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!