在Visual Studio 2015 Enterprise Edition的WinForms下,我定义了一个继承自EventArgs的通用类,如下所示:

C#版本:

/// <summary>
/// Defines the event-data of an event that notifies for item addition changes in a collection.
/// Suitable to notify changes of <see cref="ListView.ListViewItemCollection"/> for example.
/// </summary>
public class ItemAddedEventArgs<T> : EventArgs
{ }


VB.NET版本:

''' <summary>
''' Defines the event-data of an event that notifies for item addition changes in a collection.
''' Suitable to notify changes of <see cref="ListView.ListViewItemCollection"/> for example.
''' </summary>
Public Class ItemAddedEventArgs(Of T) : Inherits EventArgs
End Class


然后,我定义了一个自定义ListView类,如下所示:

C#版本:

public class ElektroListView : ListView {

    [Browsable(true)]
    [EditorBrowsable(EditorBrowsableState.Always)]
    [Localizable(false)]
    [Description("Occurs when a new item is added into the items collection of the control.")]
    public event EventHandler<ItemAddedEventArgs<ListViewItem>> ItemAdded;

}


VB.NET版本:

Public Class ElektroListView : Inherits ListView

    <Browsable(True)>
    <EditorBrowsable(EditorBrowsableState.Always)>
    <Localizable(False)>
    <Description("Occurs when a new item is added into the items collection of the control.")>
    Public Event ItemAdded As EventHandler(Of ItemAddedEventArgs(Of ListViewItem))

End Class


但是,该ItemAdded事件不会显示在Visual Studio的propertygrid的事件列表中:

c# - 通用EventArgs类未显示在WinForms设计器的propertygrid上-LMLPHP

...我认为这是因为我使用的是遗传类型参数,所以属性网格的属性初始化器机制可能无法解析它。

我的问题:什么以及如何修改我的ItemAddedEventArgs(Of T)类以便在propertygrid中将其视为“正常”事件? (这意味着,我可以双击事件名称来创建事件处理程序的自动生成的代码)

也许我只需要在此类事件的事件定义中使用某种元数据/属性类,或者可以通过实现某种TypeConverter类来解决此问题,我真的不知道,我只是在尝试提出想法...

请注意,我想保留我拥有的泛型类,而不是创建一个新的非泛型类,该类仅用于提供一种类型(ListViewItem)。



更新

现在感谢this C# example,通过这样声明事件,我可以在propertygrid中看到事件名称:

Public Delegate Sub ItemAddedDelegate(sender As Object, e As ItemAddedEventArgs(Of ListViewItem))
Public Event ItemAdded As ItemAddedDelegate


但是,当我双击propertygrid中的事件名称时,Visual Studio不会为通用类型参数生成类型名,也不会为VB.NET生成句柄子句。它生成以下代码:

Private Sub ElektroListView1_ItemAdded(sender As Object, e As ItemAddedEventArgs(Of T))
End Sub


...我还必须做些什么来解决该问题?

最佳答案

您可以创建一个从泛型事件arg派生的非泛型事件arg并使用它。

C#

public class EventArg<T> : EventArgs { /*...*/ }
public class ItemAddedEventArgs: EventArg<ListViewItem> { /*...*/ }
public class MyListView : ListView
{
    public event EventHandler<ItemAddedEventArgs> ItemAdded;
    /*...*/
}


VB.NET

Public Class EventArgs(Of T)
    Inherits EventArgs
    '...
End Class
Public Class ItemAddedEventArgs
    Inherits EventArgs(Of ListViewItem)
    '...
End Class
Public Class MyListView
    Inherits ListView
    Public Event ItemAdded As EventHandler(Of ItemAddedEventArgs)
    '...
End Class

10-02 02:23
查看更多