Search code examples
silverlight-4.0mvvmnavigationprismeventaggregator

EventAggregation quick start?


I am created a MainView that it's DataContext is a MainViewModel initialized in xaml.
The MainView contains a ContentControl that is bound to the Content property of the MainViewModel.
I added some content in the MainViewModel constructor, so that if the current user is not logged in, it automatucally loads LoginView (and correspondingly it's DataContext LoginViewModel) into this Content property.

Now my question is, what should I do when the user successfully logs in:

'To be called from the LoginCommand
Private Sub Login
  'Do Login
  If WebContext.Current.User.IsAuthenticated Then
    ' - Publish a global event to be subscribed and caught from the MainViewModel
    ' - Close LoginView
    ' - The MainViewModel should set it's Content property back
    ' to what the user initially intended to open
  End If
End Sub

How is this done?

Note: I prefer using prism's EventAggregator rathen then other stuff, but I have no clue:

  1. How to spread it out between the ViewModels
  2. How to create events (I don't need to pass parameter, nor do I need it to be generic, just Action, LoginAction - no parameters.
  3. How do I subscribe from the MainViewMode.
  4. I do NOT use MEF or Unity, nor do I use seperated modules, all my application is in one single assembly.
  5. I prefer not to write any code in the code-behind at all
  6. Answer in both VB.NET or C# are welcommed the same

Any help would be recommended


Solution

  • You can go here for info regarding the EventAggregator.

    You could also use the following code to create an instance of the EventAggregator without using MEF or Unity:

    internal static class EventAggregatorHelper
    {
      private static IEventAggregator _Current = new EventAggregator();
      public static IEventAggregator Current
      {
        get
        {
          return _Current;
        }
      }
    }
    

    And you could then call the EventAggregator like so passing in the required information to the aggregator:

    EventAggregatorHelper.Current.GetEvent<SelectedItemChangedEvent>().
      Subscribe(HandleSelectedItemChangedEvent);
    

    In this case the SelectedItemChangedEvent and the subscriber that deals with this event.

    The SelectedItemChangedEvent is a class declared as shown below:

    public class SelectedItemChangedEvent : CompositePresentationEvent<String>
    {
    } 
    

    and the subscriber would be something like this:

    internal void HandleSelectedItemChangedEvent(string viewName)
    {
       if (!String.IsNullOrEmpty(viewName))
       {
          //Do whatever you need to do here.
       }
    }
    

    The link to the Event Aggregator I posted at the start should clear most things up for you.

    Hope this helps.