Hi,@Mojtaba_Hakim . Welcome Microsoft Q&A.
Yes, you could try to collapse and expand the details.
Xaml:
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<DataGrid Name="dg1" AutoGenerateColumns="False" SelectionMode="Single" CanUserAddRows="false"
CanUserDeleteRows="False" SelectionUnit="FullRow" ItemsSource="{Binding View}" >
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="0"/>
</Style>
</DataGrid.CellStyle>
<DataGrid.RowHeaderTemplate>
<DataTemplate>
<Expander Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
</Expander>
</DataTemplate>
</DataGrid.RowHeaderTemplate>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" IsReadOnly="True" Width="100" Binding="{Binding ID}" />
<DataGridTextColumn Header="Name" IsReadOnly="True" Width="100" Binding="{Binding Name}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding Details}" CanUserAddRows="True" AutoGenerateColumns="False"
CanUserDeleteRows="True" >
<DataGrid.Columns>
<DataGridTextColumn Header="Age" IsReadOnly="True" Width="100" Binding="{Binding Title}" />
<DataGridTextColumn Header="Address" IsReadOnly="True" Width="100" Binding="{Binding Address}" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</Grid>
Codebehind:
Update:
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid x:Name="dg" ItemsSource="{Binding Details}" Initialized="dg_Initialized" >
<DataGrid.Columns>
<DataGridTextColumn Header="Age" IsReadOnly="True" Width="100" Binding="{Binding Title}" />
<DataGridTextColumn Header="Address" IsReadOnly="True" Width="100" Binding="{Binding Address}" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
The codebehind:
public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
yield return (T)child;
foreach (T childOfChild in FindVisualChildren<T>(child))
yield return childOfChild;
}
}
}
private void dg_Initialized(object sender, System.EventArgs e)
{
foreach (var datagrid in FindVisualChildren<DataGrid>(this))
{
if (datagrid.Name == "dg")
{
datagrid.Columns[0].Header = "MyAge";
datagrid.AutoGenerateColumns=false;
datagrid.CanUserAddRows = true;
datagrid. CanUserDeleteRows =true;
TextBlock x = datagrid.Columns[0].GetCellContent(datagrid.Items[2]) as TextBlock;
if (x != null)
MessageBox.Show(x.Text);
}
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.