How do I pass a variable as a CommandParameter
Solution 1
Is the CommandParameter always null or are you only checking the first time it is being executed?
It appears that the order in which you declare your properties matters in this case since setting the Command property causes the CanExecute to fire immediately before the CommandParameter has been set.
Try moving the CommandParameter property before the Command property:
<Button Content="Edit" HorizontalAlignment="Right" Height="20" Width="80"
CommandParameter="{Binding PersonModelProp}"
Command="{Binding EditPersonCommand}" />
Edit
To ensure that your events are being raised properly you should raise the CanExecuteChanged event when the PersonModelProp
value changes.
The Command:
public class EditPersonCommand : ICommand
{
public bool CanExecute(object parameter)
{
PersonModel p = parameter as PersonModel;
return p != null && p.Age > 0;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
//command implementation
}
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if(handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
And the view model:
public class PersonViewModel : ViewModelBase
{
private PersonModel _PersonModel;
private EditPersonCommand _EditPersonCommand;
///<remarks>
/// must use the parameterless constructor to satisfy <Window.Resources>
///</remarks>
public PersonViewModel()
: this(new PersonModel())
{
_EditPersonCommand = new EditPersonCommand();
}
public PersonViewModel(PersonModel personModel)
{
_PersonModel = personModel;
}
public ICommand EditPersonCommand
{
get
{
return _EditPersonCommand;
}
}
public PersonModel PersonModelProp
{
get
{
return _PersonModel;
}
set
{
_PersonModel = value;
OnPropertyChanged("PersonModelProp");
EditPersonCommand.RaiseCanExecuteChanged();
}
}
}
Solution 2
Two points to the answer:
First, as @akton mentioned, you can only bind to public properties. It doesn't have to be a DependencyProperty though.
Second, which took me some tome to figure out, is that you have to set the binding for the CommandParameter before the Command property. i.e.
<Button Content="Edit" HorizontalAlignment="Right" Height="20" Width="80"
CommandParameter="{Binding PersonModelProp}"
Command="{Binding EditPersonCommand}" />
Hope this helps :)
Solution 3
_PersonModel
is private and so cannot be accessed. Create a public property that exposes it and bind to that in the CommandParameter
. Remember to make the property a dependency property (technically not required but it helps) and the ViewModel should implement INotifyProperty changed and fire the PropertyChanged event so the binding is updated.
Solution 4
I think you have a problem in your EditPersonCommand (it not fired ok).I check it with relayCommand and it work!
This is the code:
ViewModel:
public class PersonViewModel : ViewModelBase
{
private PersonModel _PersonModel;
private ICommand _EditPersonCommand;
///<remarks>
/// must use the parameterless constructor to satisfy <Window.Resources>
///</remarks>
public PersonViewModel()
: this(new PersonModel())
{
}
public PersonViewModel(PersonModel personModel)
{
PersonModelProp = personModel;
}
public ICommand EditPersonCommand
{
get
{
if (_EditPersonCommand == null)
{
_EditPersonCommand = new RelayCommand(ExecuteEditPerson,CanExecuteEditPerson);
}
return _EditPersonCommand;
}
}
private bool CanExecuteEditPerson(object parameter)
{
PersonModel p = parameter as PersonModel;
return (p != null) && (p.Age > 0);
}
private void ExecuteEditPerson(object o)
{
}
public PersonModel PersonModelProp
{
get
{
return _PersonModel;
}
set
{
_PersonModel = value;
NotifyPropertyChanged("PersonModelProp");
}
}
}
And this RelayCommand (Fire events ok!)
public class RelayCommand : ICommand
{
#region Constants and Fields
private readonly Predicate<object> canExecute;
private readonly Action<object> execute;
#endregion
#region Constructors and Destructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
this.execute = execute;
this.canExecute = canExecute;
}
#endregion
#region Events
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
#endregion
#region Implemented Interfaces
#region ICommand
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
#endregion
#endregion
}
Xmal:
<Button Content="Edit" HorizontalAlignment="Right" Height="20" Width="80"
CommandParameter="{Binding PersonModelProp}"
Command="{Binding EditPersonCommand}" />
SwDevMan81
Twitter: @SwDevMan81 Mail: SwDevMan81 at Gmail Feel free to ping me for any questions you have. Job Title: Software Engineer Job Develop: Software for radar systems, Software GUI, real time embedded Current Languages: C#, C++, Java AS: Monroe Community College (Engineering Science) BS: University at Buffalo (Computer Science) MS: University at Buffalo (Computer Science & Engineering) MBA: Syracuse University (Business Analytics) Sites: Design Patterns Salt
Updated on July 09, 2022Comments
-
SwDevMan81 almost 2 years
I'm trying to send a variable from the ViewModel as a parameter to a command. The command looks like this:
public class EditPersonCommand : ICommand { private bool _CanExecute = false; public bool CanExecute(object parameter) { PersonModel p = parameter as PersonModel; CanExecuteProperty = (p != null) && (p.Age > 0); return CanExecuteProperty; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { } private bool CanExecuteProperty { get { return _CanExecute; } set { if (_CanExecute != value) { _CanExecute = value; EventHandler can_execute = CanExecuteChanged; if (can_execute != null) { can_execute.Invoke(this, EventArgs.Empty); } } } } }
The ViewModel looks like this:
public class PersonViewModel : ViewModelBase { private PersonModel _PersonModel; private EditPersonCommand _EditPersonCommand; ///<remarks> /// must use the parameterless constructor to satisfy <Window.Resources> ///</remarks> public PersonViewModel() : this(new PersonModel()) { } public PersonViewModel(PersonModel personModel) { _PersonModel = personModel; } public ICommand EditPersonCommand { get { if (_EditPersonCommand == null) { _EditPersonCommand = new EditPersonCommand(); } return _EditPersonCommand; } } }
The xaml looks like this:
<Button Content="Edit" HorizontalAlignment="Right" Height="20" Width="80" Command="{Binding EditPersonCommand}" CommandParameter="{Binding _PersonModel}" />
I've tried creating a property in the ViewModel instead of using the private local variable name, but that didnt work either. The
object parameter
always showsnull
in the call toCanExecute
and the button is never enabled. If I change theCommandParameter
value toHello
, then I receiveHello
in the call toCanExecute
, so I'm not sure why the variable doesnt work. Any help would be appreciated.Update: I've also tried making a public property to the model (which I dont really want to expose the model, but just tried it to see if it works, but it doesnt).
// Added this to the ViewModel public PersonModel PersonModelProp { get { return _PersonModel; } set { _PersonModel = value; OnPropertyChanged("PersonModelProp"); } }
And changed the xaml to this:
<Button Content="Edit" HorizontalAlignment="Right" Height="20" Width="80" Command="{Binding EditPersonCommand}" CommandParameter="{Binding PersonModelProp}" />
But still no luck. The ViewModel does implement
INotifyPropertyChanged
-
SwDevMan81 almost 12 yearsYeah I tried making it a public property, but that didnt work either.
-
akton almost 12 years@SwDevMan81 Was it a dependency property? Did you fire the PropertyChanged event?
-
SwDevMan81 almost 12 yearsSee my update. It is not a dependency property, but the ViewModel does implement
INotifyPropertyChanged
and thePropertyChanged
event is called. Any other ideas? -
akton almost 12 years@SeDevMan81 Time for some binary debugging. Change PersonModelProp to return a hard coded int and see whether that works. If it does, it's something wrong with the binding. If it does not work, there might be a typo in the XAML or something.
-
SwDevMan81 almost 12 yearsIf I change the Prop to an int, it still hows the parameter as null, however if I put the CommandParameter before the Command binding as others suggested, it works. Thats strange. Thx for the help, time to figure out why the order matters...
-
Admin almost 12 yearsYikes. Looking at what
Button
does, your answer is a definite improvement but still incomplete.Command.CanExecute
is never called whenCommandParameter
changes, so ifPersonModelProp
can change whenEditPersonCommand
doesn't, you won't get the behaviour you're hoping for. -
Dylan Meador almost 12 years@hvd You are correct. Like you mentioned in your original comment, a change should be made to raise the
CanExecuteChanged
event whenever thePersonModelProp
property changes. -
akton almost 12 years@SwDevMan81 That is strange. Please update the post when you find out. I, for one, would love to know why.
-
René Kåbis almost 7 yearsIn Visual Studio 2015 Community, any attempt to move
CommandParamater
aboveCommand
will be reversed upon saving the document. In other words, saving the document forces theCommandParameter
beneath theCommand
. This is default VS2015 behaviour, as it it a largely unmodified installation.