patterncsharpMinor
CommandBinding refresh on parameter changed
Viewed 0 times
changedrefreshparametercommandbinding
Problem
I need the command I am executing on a datagrids context menu to know which column was clicked on.
XAML
Code behind:
I'm having to break MVVM by having the view tell the VM command that its execution has changed because the command binding doesn't seem to refresh on the parameter changing. Is there a better way to do this?
XAML
Code behind:
private void DataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var current = e.OriginalSource as DependencyObject;
while(current != null && !(current is DataGridCell))
{
current = VisualTreeHelper.GetParent(current);
}
var cell = current as DataGridCell;
foreach (var item in dataGrid.ContextMenu.Items.OfType())
{
item.CommandParameter = cell.Column.DisplayIndex;
(item.Command as DelegateCommand)?.RaiseCanExecuteChanged();
}
}
I'm having to break MVVM by having the view tell the VM command that its execution has changed because the command binding doesn't seem to refresh on the parameter changing. Is there a better way to do this?
Solution
OK several years later and looking back I now know what I was doing wrong
this is a misuse of the command parameter
the command parameter is not a variable that you pass into the command on execution to relay the state of the application
its a constant used to specify behaviour.
if your command depends on a variable parameter you should create your own command that declares the variable as a property which can then trigger the correct events that are required to notify the view of the state change
then you could use the parameter to set if the command performs an add or a remove by passing in the string add or remove as the command parameter as this behaviour will not change during the lifespan of the command binding
this then allows the VM to update itself and work as intended
this is a misuse of the command parameter
the command parameter is not a variable that you pass into the command on execution to relay the state of the application
its a constant used to specify behaviour.
if your command depends on a variable parameter you should create your own command that declares the variable as a property which can then trigger the correct events that are required to notify the view of the state change
public class ColumnCommand:ICommand,INotifyPropertyChanged
{
public int ActiveColumn{get;set;}
//etc;
}then you could use the parameter to set if the command performs an add or a remove by passing in the string add or remove as the command parameter as this behaviour will not change during the lifespan of the command binding
this then allows the VM to update itself and work as intended
Code Snippets
public class ColumnCommand:ICommand,INotifyPropertyChanged
{
public int ActiveColumn{get;set;}
//etc;
}Context
StackExchange Code Review Q#160312, answer score: 4
Revisions (0)
No revisions yet.