I am trying to put a ContextMenu into cells of one column of a DataGrid. Clicking on a menu item of the ContextMenu should execute a command.
I can show the ContextMenu but the command is not executed and a binding error shows
ICommand TimePointOnCommand property not found on object of type Customer.
I dont want to have the ICommand on the Customer object but on the ViewModel
Is there some way to execute the command TimePointOnCommand whenever the user selects a menu item in the contect menu?
The project is as Prism project generated by the Prism template "Prism Full App"
This is my view
<Grid>
<StackPanel>
<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*" />
<DataGridTextColumn Header="Name" Binding="{Binding Id}" Width="*" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"
HorizontalAlignment="Stretch">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem
Header="An Zeitpunkt festlegen"
Command="{ Binding Path=TimePointOnCommand}" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
This is the ViewModel
using System;
using System.Collections.ObjectModel;
using Prism.Commands;
using Prism.Regions;
using PrismWpf.Core.Mvvm;
using PrismWpf.Services.Interfaces;
namespace PrismWpf.Modules.ModuleName.ViewModels
{
public class ViewAViewModel : RegionViewModelBase
{
public DelegateCommand TimePointOnCommand { get; private set; }
private ObservableCollection<Customer> _customers;
public ObservableCollection<Customer> Customers
{
get => _customers;
set => SetProperty(ref _customers, value);
}
public ViewAViewModel(IRegionManager regionManager, IMessageService messageService) :
base(regionManager)
{
TimePointOnCommand = new DelegateCommand(SetOn);
Customers = new ObservableCollection<Customer>
{
new() { Name = "John Doe", Id = 1, IsValid = true, Birthdate = new DateTime(2022, 4, 15, 10, 4, 2) },
new() { Name = "Jane Smith", Id = 2, IsValid = false, Birthdate = new DateTime(2022, 6, 15, 8, 2, 2) }
};
}
private void SetOn()
{
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
}
}
}
EDIT
The issue only happens for a ContextMenu For a button i can use
<Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl},Mode=FindAncestor},Path=DataContext.TimePointOnCommand}" >Go</Button>
But I realy need a ContextMenu here