views:

94

answers:

1

What do I have to do to get this code work?

I simply want the class to throw an event when it is finished loading and the consuming class to react to it.

It gets an error on OnLoaded saying it is null.

using System;
using System.Windows;

namespace TestEventLoaded8282
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            FileManager fm = new FileManager();
            fm.OnLoaded += new FileManager.LoadedHandler(fm_OnLoaded);
        }

        void fm_OnLoaded(object obj, FileManagerArgs args)
        {
            Console.WriteLine("the file manager is loaded: " + args.Message); 
        }
    }

    public class FileManager
    {
        public string Name { get; set; }

        public delegate void LoadedHandler(object obj, FileManagerArgs args);
        public event LoadedHandler OnLoaded;

        public FileManager()
        {
            Name = "this is the test file manager";
            OnLoaded(this, new FileManagerArgs("no errors"));
        }
    }

    public class FileManagerArgs : EventArgs
    {
        public string Message { get; set; }

        public FileManagerArgs(string message)
        {
            Message = message;
        }
    }
}
+2  A: 

This code calls OnLoaded before it attaches an event handler:

public Window1() {
    InitializeComponent();
    FileManager fm = new FileManager();
   // The next line attaches a handler, but
   // not until the constructor finishes
}

Which executes the following:

public FileManager() {
        Name = "this is the test file manager";
        OnLoaded(this, new FileManagerArgs("no errors")); // No handler yet!
}

To fix this, require the listener delegate as a FileManager constructor parameter, and attach it before calling OnLoaded:

public FileManager(LoadedHandler handler) {
        this.OnLoaded += handler;
        Name = "this is the test file manager";
        OnLoaded(this, new FileManagerArgs("no errors"));
}
Jeff Sternal
thanks, that helped me to get my code to ask the question I originally wanted to post: http://stackoverflow.com/questions/2230064/how-can-i-make-consuming-custom-events-on-my-classes-optional, perhaps its the same issue, I'll work through this code here.
Edward Tanguay
Excellent! A couple other guys got to your follow-up question first, blast it. :)
Jeff Sternal