My question is how to trigger a ViewModel method from the model.
I am developing a WPF application using MVVM. So I have a button, SubmitMedPrescCommand
, (implemented using Relay Command) and a Combobox (SelectedMedPrescRepeat
) that is binded to a model. When the user selects the dropdown the PropertyChange event is raised in the property of the model but I need to call the CanExecute (in theViewModel) in order to enable the button.
A sample of my code is listed below. Any help would be appreciated ! Thanks in advance !
The viewmodel is this:
public class EpCreateMedicineViewModel : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public ICommand SubmitMedPrescCommand { get; set; }
public EpCreateMedicineViewModel()
{
SubmitMedPrescCommand = new RelayCommand<MedicinePrescriptionForSubmission>(ExecuteSubmitMedPrescCommand, CanExecuteSubmitMedPrescCommand);
}
private MedicinePrescriptionForSubmission _medicinePrescForSubm;
public MedicinePrescriptionForSubmission MedicinePrescForSubm
{
get { return _medicinePrescForSubm; }
set
{
if (value != this._medicinePrescForSubm)
{
this._medicinePrescForSubm = value;
OnPropertyRaised("MedicinePrescForSubm");
}
}
}
public bool CanExecuteSubmitMedPrescCommand(object parameter)
{
if (_medicinePrescForSubm.MedicineForSubmGeneralInfo.SelectedMedPrescRepeat!=null)
{
return true;
}
else
{
return false;
}
}
}
and the Model where the property belongs:
public class MedicinePrescriptionForSubmission
{
public MedicineForSubmGeneralInfo MedicineForSubmGeneralInfo { get; set; }
public class MedicineForSubmGeneralInfo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private MedicinePrescriptionRepeat _selectedMedPrescRepeat; // THE PROPERTY THAT THE COMBOBOX IS BINDED TO
public MedicinePrescriptionRepeat SelectedMedPrescRepeat
{
get { return _selectedMedPrescRepeat; }
set
{
_selectedMedPrescRepeat = value;
OnPropertyRaised("SelectedMedPrescRepeat");
//CanExecuteSubmitMedPrescCommand(_selectedMedPrescRepeat); // THE METHOD OF THE VIEWMODEL THAT I WANT TO BE TRIGERRED WHEN MedicinePrescriptionRepeat changes
}
}
private void OnPropertyRaised(string propertyname)
{
PropertyChangedEventHandler handle = PropertyChanged;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
}
}