无法在Silverlight中折叠datagrid中的第一行

时间:2015-03-11 15:56:28

标签: silverlight datagrid

我使用的是Silverlight数据网格控件,默认情况下应该显示为“折叠”。我在msdn中找到了示例代码。但它显示错误消息“指定的参数超出了有效值的范围。参数名称:索引。”。以下是我的代码。

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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我通过异步调用填充datagrid。因此无法检查此呼叫是否已完成。在完成在datagrid中填充数据之前,将调用我的collapse方法。所以从其中一个站点找到了解决方案。以下是解决方案。

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