Silverlight:如何通过数据上下文获取DataGrid中的数据网格行

时间:2011-09-14 14:16:27

标签: silverlight datagrid datacontext selecteditem

在给定Silverlight数据网格的情况下,如何找到具有特定数据上下文的相应数据网格行?

1 个答案:

答案 0 :(得分:5)

这是我用这种方法编写的方法,利用各种自动化操作器:

public DataGridRow GetDataGridRowByDataContext(DataGrid dataGrid, object dataContext)
{
    if (null != dataContext)
    {
        dataGrid.ScrollIntoView(dataContext, null);

        DataGridAutomationPeer automationPeer = (DataGridAutomationPeer)DataGridAutomationPeer.CreatePeerForElement(dataGrid);

        // Get the DataGridRowsPresenterAutomationPeer so we can find the rows in the data grid...
        DataGridRowsPresenterAutomationPeer dataGridRowsPresenterAutomationPeer = automationPeer.GetChildren().
            Where(a => (a is DataGridRowsPresenterAutomationPeer)).
            Select(a => (a as DataGridRowsPresenterAutomationPeer)).
            FirstOrDefault();

        if (null != dataGridRowsPresenterAutomationPeer)
        {
            foreach (var item in dataGridRowsPresenterAutomationPeer.GetChildren())
            {
                // loop to find the DataGridCellAutomationPeer from which we can interrogate the owner -- which is a DataGridRow
                foreach (var subitem in (item as DataGridItemAutomationPeer).GetChildren())
                {
                    if ((subitem is DataGridCellAutomationPeer))
                    {
                        // At last -- the only public method for finding a row....
                        DataGridRow row = DataGridRow.GetRowContainingElement(((subitem as DataGridCellAutomationPeer).Owner as FrameworkElement));

                        // check this row to see if it is bound to the requested dataContext.
                        if ((row.DataContext) == dataContext)
                        {
                            return row;
                        }

                        break; // Only need to check one cell in each row
                    }
                }
            }
        }
    }

    return null;
}