我想从.NET类中引发一个事件,并在Silverlight代码中接收此事件(在浏览器外,使用SL4中添加的COM互操作支持)。
有人能在我的代码中指出问题吗?我是否可能需要做更多属性修饰的界面样板才能使其正常工作?
代码:
我不是编写本机COM代码,而是编写.NET代码并通过COM interop公开它。
我的事件提升.NET类看起来像这样:
using System;
namespace TestComInterop2 {
public class TestClass {
public event EventHandler TestEvent;
public void Fire() {
if (TestEvent != null)
TestEvent(this, EventArgs.Empty);
}
}
}
我的SL4客户端代码如下所示:
...
private delegate void HandlerDelegate(dynamic sender, dynamic eventArgs);
private void TestEventSinking(object sender, RoutedEventArgs e)
{
// Create instance of COM-registered .NET class
var testClass = AutomationFactory.CreateObject("TestComInterop2.TestClass");
// Subscribe to event (second line fails with System.Exception)
//
// "Failed to add event handler. Possible reasons include: the object does not
// support this or any events, or something failed while adding the event."
//
AutomationEvent testEvent = AutomationFactory.GetEvent(testClass, "TestEvent");
testEvent.AddEventHandler(new HandlerDelegate(HandleTestEvent));
// Fire the event
testClass.Fire();
}
private void HandleTestEvent(object sender, object eventargs)
{
MessageBox.Show("Event fired");
}
...