2010-08-25 50 views
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"); 
} 

... 

回答

2

使用[ComSourceInterface]属性上你的课。相关的MSDN Library主题is here