Hello,
I have below code with OnDataRecordPresenterContextMenuOpening that attach contextMenu to the grid and ExportExecuted is the command handler.
When ExportExecuted is invoked, I was expecting the sender of it to be XamDataGrid instance (as I do exportMenuItem.CommandTarget = grid), instead I am getting the sender as my window instance,
Any idea what I am doing wrong here? Thanks in advance.
Muthu
--------
EventManager.RegisterClassHandler(typeof(DataRecordPresenter), DataRecordPresenter.ContextMenuOpeningEvent, new ContextMenuEventHandler(OnDataRecordPresenterContextMenuOpening));
this.CommandBindings.Add(new CommandBinding(_exportCommand, ExportExecuted, ExportCanExecute));
public void OnDataRecordPresenterContextMenuOpening(object sender, ContextMenuEventArgs e) { var grid = (sender as DataRecordPresenter).DataPresenter as XamDataGrid;
if (grid.ContextMenu == null) { MenuItem exportMenuItem = new MenuItem { Header = "_Export", Name = "mnuExport", Command = _exportCommand }; exportMenuItem.CommandParameter = grid; exportMenuItem.CommandTarget = grid; ContextMenu gridContextMenu = new ContextMenu(); gridContextMenu.Items.Add(exportMenuItem); grid.ContextMenu = gridContextMenu; } }
void ExportExecuted(object sender, ExecutedRoutedEventArgs e) {
var grid = sender as XamDataGrid;. // Why this is NULL?
}--------
nmuthu said: Btw, when I was binding the command to window earlier, I was getting the "sender" as window as you described but the e.OriginalSource is instance of dockManager (my grid is hosted inside a DockManager ContentPane)
Btw, when I was binding the command to window earlier, I was getting the "sender" as window as you described but the e.OriginalSource is instance of dockManager (my grid is hosted inside a DockManager ContentPane)
nmuthu said: Just to clarify, what is the usage of “MenuItem.CommandTarget” as MSDN describes it as "Gets or sets the target element on which to raise the specified command"
Just to clarify, what is the usage of “MenuItem.CommandTarget” as MSDN describes it as "Gets or sets the target element on which to raise the specified command"
Thanks guys. Binding the command to grid allowed me to get "sender" and e.OriginalSource as grid instance.
Just to add to what Alex said, the sender is always the object on which you have hooked the event - which as Alex mentions is probably the window in this case. The e.OriginalSource would be the source of the event which in the case of a command being executed for a given target would be the target of the command which in this case would be the grid.
Hello Muthu,
This is probably because you are adding this command binding in the Window's CommandBindings collection. Have you tried adding it to the XamDataGrid's CommandBindings collection?