I'm learning ICommands in WPF and I ran into a problem with some simple code. I have a Button with a Command. If I set the command parameter to a static value like this, CommandParameter="100"
, the value of the parameter
argument in CanExecute is 100, however when I set the value of the command parameter via binding like this CommandParameter="{Binding}"
, the value of the parameter
argument in CanExecute is null.
Here's my ICommand:
internal class MyCommand : ICommand
{
public bool CanExecute(object parameter) //parameter is null
{
var datacontext = parameter as MyDataContext;
if (datacontext == null)
return false;
return datacontext.IsChecked == true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
throw new NotImplementedException();
}
}
Here's the XAML code. Notice that I'm setting the CommandParameter before setting the Command. I got that from here. Again, if I change the CommandParameter to somwthing like CommandParameter="100"
, the code acts as I would expect (i.e., the parameter is 100, not null).
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<cmd:MyCommand x:Key="kCmd" />
</StackPanel.Resources>
<CheckBox Content="Check this to enable button" IsChecked="{Binding IsChecked}" />
<Button Content="Click" CommandParameter="{Binding}"
Command="{StaticResource kCmd}" />
</StackPanel>
Here's my MainWindow code-behind. Here, I'm setting the DataContext before calling InitializeComponent()
. While debugging, I found that InitializeComponent()
triggers a call to the ICommand's CanExecute(object)
.
public MainWindow()
{
this.DataContext = new MyDataContext();
InitializeComponent();
}
My MyDataContext
class is pretty simple, so I left it out.