1
我想從.NET類中引發事件,並在Silverlight代碼中接收此事件(瀏覽器外,使用SL4中添加的COM互操作支持)。如何從Silverlight下沉COM事件?
任何人都可以指出我的代碼中的問題?我是否可能需要做更多屬性裝飾的界面樣板才能使這個工作?
代碼:
而不是編寫本地COM代碼,我寫的.NET代碼,並通過COM互操作曝光。
我的事件提高.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");
}
...