I am learning ICommands in WPF and I am having 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, the CommandParameter="100"argument value parameterin CanExecute is 100, however, when I set the command parameter value through a binding like this CommandParameter="{Binding}", the argument value parameterin CanExecute is null.
Here is my icommand:
internal class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
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();
}
}
XAML. , CommandParameter . . , CommandParameter CommandParameter="100", , (.. 100, 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>
MainWindow. DataContext InitializeComponent(). , InitializeComponent() ICommand CanExecute(object).
public MainWindow()
{
this.DataContext = new MyDataContext();
InitializeComponent();
}
MyDataContext , .