I’m new to WPF and MVVM so bear with me.
Basically, I am creating an application to enable users to enter their organisation details into a database.
within my WPF application I’m creating, I have a View Model that contains properties, commands and entity framework methods (I know this isn’t the correct way to use MVVM, but I’m learning slowly how to achieve it).
On one of my views, it is a tab control, allowing a user to enter different organisation details into the database and then, on another view, I have a data grid to show what they have entered to enable the user to update the content when needed.
which leads me to my question. So far I have validated my commands so that when certain fields are empty, then the button will not be active but once they have been entered, they will be activated. Like so;
private ICommand showAddCommand;
public ICommand ShowAddCommand
{
get
{
if (this.showAddCommand == null)
{
this.showAddCommand = new RelayCommand(this.SaveFormExecute, this.SaveFormCanExecute);//i => this.InsertOrganisation()
}
return this.showAddCommand;
}
}
private bool SaveFormCanExecute()
{
return !string.IsNullOrEmpty(OrganisationName) && !string.IsNullOrEmpty(Address) && !string.IsNullOrEmpty(Country) && !string.IsNullOrEmpty(Postcode)
&& !string.IsNullOrEmpty(PhoneNumber) && !string.IsNullOrEmpty(MobileNumber) && !string.IsNullOrEmpty(PracticeStructure) && !string.IsNullOrEmpty(PracticeType) && !string.IsNullOrEmpty(RegistrationNumber);
}
private void SaveFormExecute()
{
InsertOrganisations();
}
Xaml:
<Button Content="Save" Grid.Column="1" Grid.Row="18" x:Name="btnSave" VerticalAlignment="Bottom" Width="75" Command="{Binding ShowAddCommand}"/>
But what I was hoping to achieve is that, once a user has entered in 1 organisation into the database, then the command doesn’t become active altogether and prevents the user from entering another organisation by accident. the purpose is to only allow 1 organisation to be added, no more or no less.
Is this possible?
Two things. 1), I’d recommend editing your RelayCommand to take an Action as follows:
This may not help your immediate issue, but it will make your code more reusable, as you’ll be able to bind certain elements from your View as parameters in your ICommand for both CanExecute testing and Execution (or if you won’t require this, just pass null as the object parameter in the ICommand.Execute and don’t bind anything to CommandParameter in the View)
Furthermore, in your RelayCommand, make sure you are overriding CanExecuteChanged as follows:
This will trigger your ICommand to recheck CanExecute when changes are made by the user (and is most likely the piece that you’re missing).
Finally, once this is done, it’s just a matter of including your criteria in CanExecute (either from the CommandParameter OR from something in your VM).
I hope this helps.