Using Notifications

The JoobContext class enables you to register for notifications; that is, subscribe to events. The RegisterClassNotificationHandler method, which registers for notifications for a specific event that happens to any instance of the specified class, has the following parameters.

There is also an UnregisterClassNotificationHandler method.

One use of notifications is to automatically refresh the information displayed in an application when the underlying information changes. The instructions in this section are intended to make the Refresh button redundant.

  1. In the MainWindow.xaml.cs code file, add a private refresh method with the same code as the btnRefresh_Click method

    private void refresh()
    {
        lstCustomers.ItemsSource = bank.AllCustomers;
        lstCustomers.DisplayMemberPath = "LastName";
    }
  2. In the form constructor, register to be notified when Customer objects are created. The customerCreatedNotificationHandler method, which you will code shortly, is the event handler for the notification.

    public MainWindow()
    {
        InitializeComponent();
        context = new JoobContext();
        bank = context.FirstInstance<Bank>();
        context.RegisterClassNotificationHandler(typeof(Customer), 
                                           NotificationEventConstants.SystemCreate, 
                                           customerCreatedNoteHandler);
  3. Add a customerCreatedNoteHandler notification event handler method.

    private void customerCreatedNoteHandler(object sender, NotificationEventArgs e)
    {
        MessageBox.Show("Customer added");
        // cannot run refresh() yet because not on GUI thread
    }
  4. Run the BankingApp application form and enter data for a new customer. Click the Add button to add the customer. A message box stating that the customer has been added is then displayed.

Notifications are delivered on a separate thread from the GUI thread on which the application runs. The notifications thread can display a message box, as you have seen, but cannot see the list box or other controls on the form. Consequently the refresh method cannot be executed directly from this thread.