I have a DataGrid within an ItemsControl, like shown below (Representing a collection within a collection).
When I place a button within a DataGrid cell, can I bind the command so that 2 parameters are passed into it? In this case I want to pass the instances of (Item,SubItem) that corresponds to the specific button.
How can I do this?
From what I have researched, I can make a helper class, which has the (Item,SubItem) set, and then pass that into the command. But I don't know how to go about actually doing it.
The code snippets below show what I am trying to do.
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<DataGrid ItemsSource="{Binding SubItems}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Width="60">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding ???, Path=DataContext.Command}"
CommandParameter="{Binding ???}">
<TextBlock Text="x"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
class ViewModel
{
public ViewModel()
{
Items = new ObservableCollection<Item>;
}
public ObservableCollection<Item> Items { get; set; }
public RelayCommand Command => new RelayCommand(execute => SomeMethod((Item, SubItem) execute), canExecute => true);
private void SomeMethod(Item item, SubItem subItem)
{
//Method Logic
}
}
class Item
{
public Item()
{
SubItems = new ObservableCollection<SubItem>;
}
public ObservableCollection<SubItem> SubItems { get; set; }
public string Name;
public double Property;
etc...
}
class SubItem
{
public SubItem()
{
}
public string Name;
public double Property;
etc...
}
Item,SubItem)" be able to easily interact with each other. This is the reason (in my mind) for setting up a good parenting hierarchy that maintains itself through any changes to the respective collections.