This project is read-only.

Sample 1

Simple demo of EventAggregator
Goal is to run the WPF application and show MainWindow

Start by creating default WPF application in Visual Studio.

Remove the default StartupUri declaration in the App.xaml.

App.xaml
<Application x:Class="EventAggregatorSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

App.xaml.cs
using System.Windows;
using EventAggregator;

namespace EventAggregatorSample
{
    public partial class App : Application
    {
    }
}

Now lets show our MainWindow (default MainWindow created by Visual Studio is just fine for our sample).

We need to do two things. First, send an event message notifying that application has started up. Second, in MainWindow class provide this event with a handler calling Show() method.

Our AppStartup event will come from the App class. Modify your App.xaml.cs file as show below.

App.xaml.cs
using System.Windows;
using EventAggregator;

namespace EventAggregatorSample
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Current.MainWindow = new MainWindow();

            this.Send(EventId.Default.AppStartup);
        }
    }
}

Here we have override method OnStartup(...) where instance of a MainWindow class is created. Also we have a call to extension method Send(...).

More about Send extension method

In case we don't want to provide event message with additional data, only event ID is required to be specified. So we create EventId.settings file to store all our event IDs. Event IDs must be of integer type and have distinct values within EventId collection.

Also you can use enum to store your event IDs and cast them to int:

this.Send((int)EventId.AppStartup);

EventId.cs
public enum EnumEventId
{
    AppStartup
}


By now if we start our sample project nothing is going to happen. To fix this let's change the contents of MainWindow code-behind file.

MainWindow.xaml.cs
using System.Windows;
using EventAggregator;

namespace EventAggregatorSample
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Subscribe(EventId.Default.AppStartup, HandleAppStartup);
        }

        private void HandleAppStartup(EventMessage eventMessage)
        {
            Show();
        }
    }
}

We added Subscribe(...) extension method to get notification when our application starts and provided handler for this event.

More about Subscribe extension method

MainWindow will react to AppStartup event by calling Show() method.

Now run your project and see what happens.

Last edited Apr 8, 2012 at 1:46 PM by DarkVasya, version 4

Comments

No comments yet.