I have been working through some of the examples of MVVM & WPF and while doing some debugging I find that the RelayCommand associated with a button on my view is constantly firing (executing the associated ImportHoursCommand) as soon as the program starts.
Here are the code snippets:
View
<Button x:Name="ImportHoursButton" Content="Import Hours"
Command="{Binding ImportHoursCommand}"
Height="25" Width="100" Margin="10"
VerticalAlignment="Bottom" HorizontalAlignment="Right"
Grid.Row="1" />
ViewModel
private RelayCommand _importHoursCommand;
public ICommand ImportHoursCommand
{
get
{
if (_importHoursCommand == null)
{
_importHoursCommand = new RelayCommand(param => this.ImportHoursCommandExecute(),
param => this.ImportHoursCommandCanExecute);
}
return _importHoursCommand;
}
}
void ImportHoursCommandExecute()
{
MessageBox.Show("Import Hours",
"Hours have been imported!",
MessageBoxButton.OK);
}
bool ImportHoursCommandCanExecute
{
get
{
string userProfile = System.Environment.GetEnvironmentVariable("USERPROFILE");
string currentFile = @userProfile + "\\download\\test.txt";
if (!File.Exists(currentFile))
{
MessageBox.Show("File Not Found",
"The file " + currentFile + " was not found!",
MessageBoxButton.OK);
return false;
}
return true;
}
}
If I put a breakpoint on the 'string userProfile = ...' line and run the program, Visual Studio will stop on the breakpoint and continue to stop on the breakpoint everytime I click the debug 'Continue' button. If I don't have a breakpoint the program appears to run OK but should this command always be checking if it can execute?
I am using the RelayCommand from Josh Smith's article here.