无法在 Silverlight 中折叠数据网格中的第一行

Not able to collapse the first row in datagrid in Silverlight

我使用的是 Silverlight 数据网格控件,默认情况下应该显示 'collapsed'。我在 msdn 中找到了示例代码。但它显示错误消息 "Specified argument was out of the range of valid values. Parameter name: index. " 。下面是我的代码。

private void CollapseGrid()
        {
            PagedCollectionView pcv = MyGrid.ItemsSource as PagedCollectionView;
            try
            {
                foreach (CollectionViewGroup group in pcv.Groups)
                {
                    MyGrid.CollapseRowGroup(group, true);
                    MyGrid.ScrollIntoView(group, null);
                }
            }
            catch (Exception ex)
            {
                // Could not collapse group.
                MessageBox.Show(ex.Message);
            }
        }

我做错了什么?

我已解决问题。我正在通过异步调用填充数据网格。所以没有办法检查这个调用是否完成。在数据网格中填充数据完成之前,将调用我的折叠方法。所以从其中一个站点找到了解决方案。下面是解决方案。

void myDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    myDataGrid.LoadingRow -= new EventHandler<DataGridRowEventArgs>(myDataGrid_LoadingRow);
    this.Dispatcher.BeginInvoke(delegate
    {
        PagedCollectionView pcv = (PagedCollectionView)myDataGrid.ItemsSource;
        foreach (CollectionViewGroup groupname in pcv.Groups)
        {
          myDataGrid.CollapseRowGroup(groupname, true);
        }
     });
}

在xaml的datagrid部分,我们需要添加这个事件。

<sdk:DataGrid LoadingRow = "myDataGrid_LoadingRow"  ItemsSource="{Binding MyBindingSource}">