Night Walker
Night Walker

Reputation: 21280

RelayCommand CanExecute behavior

I have following command:

<Button x:Name="bOpenConnection" Content="Start Production"
        Grid.Row="0" Grid.Column="0"
        Height="30" Width="120" Margin="10"
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Command="{Binding Path=StartProductionCommand}"/>

StartProductionCommand = new RelayCommand(OpenConnection, CanStartProduction);

private bool CanStartProduction()
{
   return LogContent != null && !_simulationObject.Connected;
}

CanStartProduction is checked only when I re-size the UI and not updated on the fly. Any idea why it's not updated every time they change the values ?

Upvotes: 8

Views: 12810

Answers (2)

Boas Enkler
Boas Enkler

Reputation: 12557

You can call RaiseCanExecuteChanged in the For example PropertyChanged Eventhandler.

Command states are not refreshed very often.

Sometime ago I read a good article about it. I will post it later on.

see also http://joshsmithonwpf.wordpress.com/2008/06/17/allowing-commandmanager-to-query-your-icommand-objects/

see also Refresh WPF Command

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292695

The CommandManager has no way of knowing that the command depends on LogContent and _simulationObject.Connected, so it can't reevaluate CanExecute automatically when these properties change.

You can explicitly request a reevaluation by calling CommandManager.InvalidateRequerySuggested. Note that it will reevaluate CanExecute for all commands; if you want to refresh only one, you need to raise the CanExecuteChanged event on the command itself by calling StartProductionCommand.RaiseCanExecuteChanged.

Upvotes: 18

Related Questions