I've been using MVVM pattern for a while now, but I still run into problems in real-life situations. Here's another one: I use commanding and bubble up the event to be handled in the ViewModel. So far, so good. But the project for which I'm using MVVM is actually a class library. Once I run the command code, I need to be able to send an object back to the calling application. What are suggested ways to do so?
Specifically: In my calling app I have a XAML page bound directly to the library's ViewModel, which contains an object "Thing1". When a button is clicked, a method in the ViewModel is called (call it "CopyThing1()"). It copies "Thing1" to create "Thing2". Then I need to send "Thing2" back to the calling app.
Thanks!!!
If Thing2 is another property on your viewmodel, you can use normal INotifyPropertyChanged to inform the UI of the change.
You could also use Prism's
EventAggregator
for a more decoupled approachThe ideal approach is to define a new class inherited from ICommand as follows:
Note that Execute2 returns the value just like a normal function. Here is how to use it.
Calls Execute2 instead of Execute will returns the value.
Commands don't return values, they change the state of your application. In case of ICommands attached to ViewModels it's pretty simple, because you can do this by simply mutating the ViewModel when the command is executed.
Using the RelayCommand from Josh Smith's excellent MVVM article:
After you call
myVM.MutateCommand.Execute(new object());
you can access the new value ofmyVM.Thing
.Although the info on Commanding was clear and correct, it couldn't be applied in my case because the reponse required to happen was in a calling application NOT using MVVM and it was not to be UI response only. I did investigate Prism, but found it too complex for what I need at the moment. I ended up raising and handling events, as described here--> WPF MVVM Correct Way to Fire Event on View From ViewModel