如何阻止DataGrid在属性更改时折叠RowDetails?

时间:2015-12-12 18:48:28

标签: c# wpf datagrid

给定一个带有切换行详细信息按钮的DataGrid。为什么在更改属性时它会折叠细节?

每当列使用时,它都会折叠细节:

UpdateSourceTrigger=LostFocus

每当在详细信息视图中更新属性时,它也会折叠它。

有没有办法让它保持开放?该行仍处于选中状态。

XAML:

RowDetailsVisibilityMode="Collapsed"

                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button x:Name="buttonDetails" Content="Hello" ButtonBase.Click="Details_Click"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

C#:

    // Load stuff from db
    _context.JobCollection.Load();

    // Set source with db stuff
    jobViewSource.Source = _context.JobCollection.Local;



    private void Details_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // the original source is what was clicked.  For example 
            // a button.
            DependencyObject dep = (DependencyObject)e.OriginalSource;

            // iteratively traverse the visual tree upwards looking for
            // the clicked row.
            while ((dep != null) && !(dep is DataGridRow))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            // if we found the clicked row
            if (dep != null && dep is DataGridRow)
            {
                // get the row
                DataGridRow row = (DataGridRow)dep;

                // change the details visibility
                if (row.DetailsVisibility == Visibility.Collapsed)
                {
                    row.DetailsVisibility = Visibility.Visible;
                }
                else
                {
                    row.DetailsVisibility = Visibility.Collapsed;
                }
            }
        }
        catch (System.Exception)
        {
        }
    }

1 个答案:

答案 0 :(得分:0)

很少有人建议改变:

  1. RowDetailsVisibilityMode="Collapsed"应用于您的DataGrid。

  2. 您点击按钮应如下所示:

    private void Details_Click(object sender, RoutedEventArgs e)
    {
       DataGridRow row = (DataGridRow)Dgrd1.ItemContainerGenerator.ContainerFromItem(Dgrd1.SelectedItem);
    
       if (row.DetailsVisibility == System.Windows.Visibility.Visible)
           row.DetailsVisibility = System.Windows.Visibility.Collapsed;
       else
           row.DetailsVisibility = System.Windows.Visibility.Visible;
    }