It would be much easier to do it via bindings. You could add a collection of DetailElements to each Element of your dataGrid1's ItemsSource. Now all you have to do is binding this collection to your dataGrid2' ItemsSource and it gets automatically populated with data through the binding.
public class DataGrid1SourceItem
{
public ObservableCollection<DetailItem> DetailItems {get;set;}
}
The XAML:
<Grid>
<my:DataGrid Name="dataGrid1" ItemsSource="{Binding}">
<my:DataGrid.RowDetailsTemplate>
<DataTemplate>
<my:DataGrid Name="dataGrid2" ItemsSource="{Binding Path=DetailItems}"></my:DataGrid>
</DataTemplate>
</my:DataGrid.RowDetailsTemplate>
</my:DataGrid>
</Grid>
EDIT: To search your database depending on the DataGrid cells value, you have to get this value into your ViewModel. To do this create a property (in my example ProductName
) and bind it to the DataGridColumn's Binding property (Mode=TwoWay). Then you could have a private field which holds all products and filter this field in the dataGrid2 ItemsSources collection:
public class DataGrid1SourceItem
{
private List<DetailItems> _allDetailItems = new List<DetailItems>();
public IEnumerable<DetailItem> DetailItems
{
get { return _allDetailItems.Where(item => item.Name == ProductName); }
}
public DataGrid1SourceItem()
{
// load your products into _allDetailItems
}
private string _productName;
public string ProductName
{
get { return _productName; }
set
{
_productName= value;
OnPropertyChanged("ProductName");
OnPropertyChanged("DetailItems");
}
}
}