Why is my ICommand.CanExecute (object) parameter null when I set CommandParameter to some kind of Binding, but not null when I set it to some static value?

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) //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();
    }
}

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 , .

+4
2

CanExecute Loaded FrameworkElement CanExecuteChanged . , DataTemplate s, .

:

 <DataTemplate x:Key="MyTemplate">
            <Grid Loaded="HandleLoaded">
 ...

:

 void HandleLoaded(object sender, RoutedEventArgs e)
 {
     var viewModel = this.DataContext as ViewModel;
     if (viewModel != null)
     {
         viewModel.DoItCommand.RaiseCanExecuteChanged();
     }
 }

, , IsAsync=True. . , , .

: {Binding DoItCommand, IsAsync=True}

+2

CanExecuteChanged -event MyCommand InitializeComponent(). , CanExecute(object) MyCommand , .

+1

All Articles