0

我正在玩活动/代表,我经常收到以下错误:

PresentationFramework.dll 中出现“System.Reflection.TargetInvocationException”类型的未处理异常

附加信息:调用的目标已引发异常。

我的代码如下:

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;
    }
}

显然,我在另一个位置有代码来打开 TestWindow 对象:

TestWindow testWindow = new TestWindow();

testWindow.TestEvent += this.TestMethod;

和:

private void TestMethod(object sender, EventArgs e)
{
}
4

2 回答 2

1

您在构造函数中调用事件,这意味着在窗口初始化期间,因此当时TestEvent为 null。为 the 添加一个空检查TestEvent并在构造函数之外的某个方法中调用它,检查是否TestEvent有一个订阅者分配给,即它不为空。

编辑:

下面是一段代码来演示:

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
        }
    }
于 2013-12-27T05:28:56.920 回答
-1

您在方法调用之前缺少以下行

   TestEvent += new TestDelegate(TestMethod);

构造函数中的正确代码是。

 public TestWindow()
        {
            this.InitializeComponent();

            TestEvent += new TestDelegate(TestMethod);

            this.TestEvent(this, new EventArgs());
        }
于 2013-12-27T04:47:00.400 回答