I had been using RelayCommand
that I copied from an article (probably this one), and the CreateExamCommand
below worked fine, with CanExecute
bound to whether `Name was empty.
<UniformGrid Columns="2" DockPanel.Dock="Bottom">
<Button Content="Cancel" Command="{Binding CancelCommand}" HorizontalAlignment="Left"/>
<Button Content="Create" Command="{Binding CreateExamCommand}" HorizontalAlignment="Right"/>
</UniformGrid>
<StackPanel VerticalAlignment="Center">
<TextBox Name="textBox" Tag="Exam Name"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
public RelayCommand CreateExamCommand => new RelayCommand(
() => CreateExam(Name, Date),
() => !string.IsNullOrEmpty(_name)
);
However, I just installed MVVMLightLibs, to replace my manually copied code (and deleted my versions of RelayCommand
). Now the CanExecute
method of CreateExamCommand
is broken.
I put some WriteLine
s inside the CanExecute
and it appears to only run when the view(model) is loaded for the first time.
How do I fix this?
It depends on which version of MVVMLight's RelayCommand you're using.
If you have the namespace "GalaSoft.MvvmLight.CommandWpf" then your command will use the CommandManager object and automatically refresh CanExecute after each keystroke or mouse click.
If you have "GalaSoft.MvvmLight.Command" then you have to trigger CanExecute manually - add CreateExamCommand.RaiseCanExecuteChanged()
in the setter of your Name property.