How can I bind a command parameter from MenuItem to parent Grid DataContext?
I have a DataGrid with ContextMenu, binding the menu items to ViewModel commands, but the command parameter is always null.
I use Tag parameter into DataGrid to get access into DataContext and use the desired command but could figure it out to get the binding data from every row to use as a command parameter.
I had already looked into many answers here, but couldn't find anyone that works, the command parameter inside the ViewModel is called and command parameter is always null.
C#
public class People
{
public int Id { get; set; }
public string Name { get; set; }
}
public class PeopleWindowViewModel
{
public List<People> Peoples { get; set; }
public PeopleWindowViewModel()
{
// populate Peoples list...
}
public ICommand RemoveCommand
{
get
{
return RelayCommand.Create((m) =>
{
// m always null
});
}
}
}
public class PeoplePage : Page
{
public PeoplePage()
{
InitializeComponent();
DataContext = new PeopleWindowViewModel();
}
}
XAML:
<DataGrid
Margin="0 8 0 8"
d:DataContext="{d:DesignInstance local:People}"
IsReadOnly="True"
ItemsSource="{Binding Peoples}"
Tag="{Binding DataContext,
RelativeSource={RelativeSource AncestorType={x:Type Page}}}">
<DataGrid.Columns>
<DataGridTextColumn
Binding="{Binding Id}"
Header="Id" />
<DataGridTextColumn
Binding="{Binding Name}"
Header="Name" />
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu
Tag="{Binding Path=PlacementTarget.Tag,
RelativeSource={RelativeSource Self}}">
<MenuItem
Command="{Binding PlacementTarget.Tag.RemoveCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ContextMenu}}"
CommandParameter="{Binding Path=Id,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=DataGrid}}"
Header="Remover" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Page>