Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 431
Night Walker Avatar asked Feb 25 '13 11:02

Night Walker


People also ask

What are ICommands?

The ICommand interface is the code contract for commands that are written in . NET for Windows Runtime apps. These commands provide the commanding behavior for UI elements such as a Windows Runtime XAML Button and in particular an AppBarButton .

What is RelayCommand WPF?

The RelayCommand and RelayCommand<T> are ICommand implementations that can expose a method or delegate to the view. These types act as a way to bind commands between the viewmodel and UI elements.


1 Answers

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.

like image 181
Thomas Levesque Avatar answered Oct 13 '22 11:10

Thomas Levesque