EagleBeak
EagleBeak

Reputation: 7419

Why does the button stay enabled although CanExecute of bound command is false

I have a ViewModel with an ICommand:

class MainWindowViewModel : ViewModelBase
{
    public bool CanExecute { get; set; }

    public ICommand SomeCommand { get; set; }

    public MainWindowViewModel()
    {
        CanExecute = true;

        SomeCommand = new RelayCommand(() => MessageBox.Show("Executing"), () => CanExecute);

        CommandManager.RequerySuggested += OnRefreshing;
    }

    private void OnRefreshing(object sender, EventArgs e)
    {
        Console.WriteLine("Refreshing");
    }
}

And I have a very simple binding to it in my XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <CheckBox Grid.Row="0" IsChecked="{Binding CanExecute, Mode=TwoWay}"/>
        <Button Grid.Row="1" Content="Click Me!" Command="{Binding SomeCommand}"/>
    </Grid>
</Window>

When I click on the CheckBox, CanExecute should change. I can see that CommandManager.RequerySuggested is thrown, but my button stays enabled.

What's wrong? My binding? Does this have anything to do with MVVMLight?

Upvotes: 0

Views: 646

Answers (1)

EagleBeak
EagleBeak

Reputation: 7419

The problem lies in the MVVMLight framework. Its RelayCommand was changed and does not listen to CommandManager.RequerySuggested any more. So you actually have to manually call RaiseCanExecuteChanged on the command. This sucks...

See here for a discussion on this change in MVVMLight.

Any idea, how to handle this without a ton of manual calls to RaiseCanExecuteChanged will be greatly appreciated!

Upvotes: 2

Related Questions