Question

I'm playing around with events/delegates and I constantly get the following error:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

Additional information: Exception has been thrown by the target of an invocation.

My code is as follows:

namespace Test
{
    using System;
    using System.Windows;

    public partial class TestWindow : Window
    {
        public TestWindow()
        {
            this.InitializeComponent();

            this.TestEvent(this, new EventArgs());
        }

        public delegate void TestDelegate(object sender, EventArgs e);

        public event TestDelegate TestEvent;
    }
}

Obviously, I have code in another location to open the TestWindow object:

TestWindow testWindow = new TestWindow();

testWindow.TestEvent += this.TestMethod;

And:

private void TestMethod(object sender, EventArgs e)
{
}
Was it helpful?

Solution

You are calling the event in the constructor, meaning during the window initialization, so the TestEvent is null at that time. Add a null check for the TestEvent and call it in some method other than the constructor, checking if the TestEvent has a subscriber assigned to, i.e., it is not null.

Edit:

Here is a bit of code to demonstrate:

public partial class TestWindow : Window
    {
        public TestWindow()
        {
            this.InitializeComponent();
            //don't publish event in constructor, since the event yet to have any subscriber
            //this.TestEvent(this, new EventArgs());
        }

        public void DoSomething()
        {
            //Do Something Here and notify subscribers that something has been done
            if (TestEvent != null)
            {
                TestEvent(this, new EventArgs());
            }
        }
        public delegate void TestDelegate(object sender, EventArgs e);

        public event TestDelegate TestEvent;
    }
    public class Subscriber
    {
        public Subscriber(TestWindow win)
        {
            win.TestEvent += this.TestMethod;
        }

        private void TestMethod(object sender, EventArgs e)
        {
            //Do something when the event occurs
        }
    }

OTHER TIPS

you are missing following line before method invocation

   TestEvent += new TestDelegate(TestMethod);

The correct code inside the constructor would be.

 public TestWindow()
        {
            this.InitializeComponent();

            TestEvent += new TestDelegate(TestMethod);

            this.TestEvent(this, new EventArgs());
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top