I am developing painting application in which i need to save my painting. To save i need to show save file dialog , As i am implementing MVVM pattern i can't directly use event handler. But while implementing i thought of using PropertyChanged event directoly.
I have implemented INotifyPropertyChanged in ViewModel , I have bind all commands. In save command in ViewModel i have called
OnPropertyChanged("Show Save Dialog"); // in ViewModel
and in code behind of user control I have added event handler as
ViewModel.PropertyChanged += new // in code behind of user control
System.ComponentModel.PropertyChangedEventHandler(ViewModel_PropertyChanged);
and in ViewModel_PropertyChanged i have
switch (e.PropertyName ) // in code behind of user control
{
case "Show Save Dialog": ShowSaveFileDialog();// this function shows dialog.
break;
}
This works fine in my situation but I don't know the dark side of this implementation.
Is it right ????
Right? There is no right or wrong, only the best choice at the current time. The only way for purists would be to abstract away the process of gaining such input from the user behind an interface, then create a View class which serves this interface and inject it somehow (IoC/DI, or perhaps by composition in the xaml if your ViewModels are instantiated that way).
Personally, I wouldn't spend too much time worrying about this, unless you must worry about this. I've done it both ways. For your average MVVM app, I think it is no great crime to just use a MessageBox, OpenFileDialog, etc. For heavily tested apps, you'll need to abstract it away. And there are other situations that demand it as well. For example, I have code that exists in an application and in a Visual Studio extension. VS has its own dialog types which should be used instead of, say, MessageBox. So abstraction is appropriate. But I wouldn't invest the work unless I had a reason to.