How can I expand the Datagrid data section with a button?

I am trying to implement a datagrid that works like a folder tree (i.e. each row represents a folder, and the detail view is another data file showing the files in the folder). I tried to cut my code for simplicity, so there may be errors, but here is my basic XAML layout:

<my:DataGrid Name="dataGrid1" AutoGenerateColumns="False" ItemsSource="{Binding}">
    <my:DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <my:DataGrid ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:DataGrid}}, Path=SelectedItem.Files}" AutoGenerateColumns="False" HeadersVisibility="None">
                <my:DataGrid.Columns>
                    <my:DataGridTextColumn Binding="{Binding Path=FileName}" />
                    <my:DataGridTextColumn Binding="{Binding Path=FSize}" />
                </my:DataGrid.Columns>
            </my:DataGrid>
        </DataTemplate>
    </my:DataGrid.RowDetailsTemplate>
    <my:DataGrid.Columns>
        <my:DataGridTemplateColumn CanUserResize="False" CanUserSort="False" Width="16">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="Button_Click_1">
                        <Image Source="resources/+.ico" />
                    </Button>
                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>
        <my:DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
    </my:DataGrid.Columns>
</my:DataGrid>

I am trying for a button to expand the details line, but I'm not sure how to refer to the line:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        // how do I reference a row here?
        DataGridRow row = ?
        // so I can do this:
        if (row.DetailsVisibility == Visibility.Collapsed)
            row.DetailsVisibility = Visibility.Visible;
        else
            row.DetailsVisibility = Visibility.Collapsed;
    }

I hope the question is clear ... Thanks.

+3
source share
1 answer
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        DependencyObject obj = (DependencyObject)e.OriginalSource;
        while (!(obj is DataGridRow) && obj != null)
            obj = VisualTreeHelper.GetParent(obj);

        if(obj is DataGridRow)
            (obj as DataGridRow).DetailsVisibility = Visibility.Visible;
    }

... et voilà

+6
source

Source: https://habr.com/ru/post/1706305/


All Articles