0

我有一个带有 RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected 的标准 Silverlight DataGrid

我尝试在 XAML 以及父控件的 Loaded 事件中设置此属性。在父级的 Loaded 事件中,我设置了网格的 itemsource,然后手动将选定的索引设置为 0。这不会触发 RowDetailsVisibilityChanged 事件。

但是,一旦我通过单击新行来更改选择,它就会触发。我需要访问第一个选择的行的“DetailElement”以用数据填充其中的控件。但是,我知道如何获取该 DetailElement 的唯一方法是在 RowDetailsVisibilityChanged 事件中。

这是我的代码:

void ViewAssociationUserControl_Loaded(object sender, RoutedEventArgs e)
    {
        viewAssociationsDataGrid.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
        viewAssociationsDataGrid.ItemSource = myData;
        viewAssociationsDataGrid.SelectedIndex = 0;
    }

private void viewAssociationsDataGrid_RowDetailsVisibilityChanged(object sender, System.Windows.Controls.DataGridRowDetailsEventArgs e)
    {
        if (viewAssociationsDataGrid.RowDetailsVisibilityMode == DataGridRowDetailsVisibilityMode.VisibleWhenSelected
            && e.Row.DetailsVisibility == System.Windows.Visibility.Visible)
        {
            Grid detailElement = e.DetailsElement as Grid;
            if (detailElement != null)
            {
                ListBox assocControl = detailElement.FindName("oneToManyGridPanel") as ListBox;
                UpdateOneToManyPanel(assocControl);
            }
        }
    }
4

2 回答 2

1

我想不出一种干净地处理这种情况的方法,所以我最终劫持了最初的“选择更改”事件,并且第一次自己手动触发了可见性更改事件:

private void viewAssociationsDataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        if (!initialTriggerFired) //manually fire the visibility the first time
        {
            initialTriggerFired = true;
            DataGrid dataGrid = sender as DataGrid;

            int selectedIndex = dataGrid.SelectedIndex;
            if (selectedIndex > -1)
            {
                DataGridColumn column = dataGrid.Columns[0];
                FrameworkElement fe = column.GetCellContent(dataGrid.SelectedItem);
                DataGridRow row = fe.GetAncestorOfType<DataGridRow>();

                if (row != null)
                {
                    row.DetailsVisibility = System.Windows.Visibility.Collapsed;
                    row.DetailsVisibility = System.Windows.Visibility.Visible;
                }
            }
        }
    }
于 2012-05-02T21:06:21.697 回答
0

问题是您的数据网格将所选索引默认为 0。只需viewAssociationsDataGrid.SelectedIndex = -1在您的ViewAssociationUserControl_Loaded事件处理程序中设置即可,以便在最初选择第一行时注册选择更改。

于 2012-05-21T17:00:20.677 回答