Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a View MyView and corresponding ViewModel MyViewModel. Above the MyView there is banner(user control). The banner is used by many views. Its function is to display notifications. There is a method inside the banner's code behind.

Now I have a button command in the MyView. I want to press it and send a message to the method. The implementation of the button command is in MyViewModel.

So how to call the method from MyViewModel?

Please don't tell me it is against MVVM. I know it but no choice right now.

What I have tried:

c# - How can i access a control in mvvm model in viewmodel? - Stack Overflow[^] This one is helpful. But not sure it is fitful my case.
Posted
Updated 10-Jun-18 0:22am
Comments
Richard Deeming 9-Jun-18 10:36am    
Perhaps you're looking for the mediator pattern[^]?
Member 12658724 9-Jun-18 11:16am    
Hopefully code hint is available for this particular case.

The "banner" is just another "view"; I see no issue slotting in with the "other views".

It should have it's own "model" that responds to "incoming messages" posted from "other models" (or whatever).

You do not appear to be treating it as a view but as a "user control" (?); and therefore your unhappiness.
 
Share this answer
 
Comments
Member 12658724 9-Jun-18 12:37pm    
I am not exactly understanding your input. Could you please some code assistance?

My approach, for what it's worth, would be to do something like this. Using Prism.Events, declare an event. In the following example the event's payload is a bool but you can use any object.

C#
public class DatabaseServiceIsSavedEvent : PubSubEvent<bool>
   {

   }

In the class that wishes to publish the event, have an instance of IEventAggregator aggregator then, when you want to raise the event, you can publish the event like this.

C#
aggregator.GetEvent<DatabaseServiceIsSavedEvent>().Publish(true);

In this case the payload is a bool set to true.

In the constructor of the class that you wish to receive the event, you subscribe to the event, passing in the method that you wish to be called when the event is raised. For example.
C#
aggregator.GetEvent<DatabaseServiceIsSavedEvent>()
              .Subscribe(OnIsSavedEvent);

The OnIsSavedEvent method is something like this.
C#
public void OnIsSavedEvent(bool isSaved)
       {
           IsModified = !isSaved;
       }

 
Share this answer
 
Comments
Member 12658724 10-Jun-18 7:50am    
I will try it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900