Dynamically adding ToolStripMenuItems to a MenuStrip (C#/ Winforms)

后端 未结 4 1497
小蘑菇
小蘑菇 2021-02-18 18:53

I have my solution implemented (basic solution) and I\'m happy.

Problem is when I add new items to a ToolStripItemCollection using the \'Add\' method, I get a few overl

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-18 19:16

    I was having similar issues as Philip Wallace. It's important to note the difference between a ToolStripItem, and a ToolStripMenuItem. I was adding ToolStripItems to a ToolStripMenuItem's DropDownItems, and they would show up, and have all properties set correctly, and accessible in code, but they would not show any text! Switching to a ToolStripMenuItem solved this.

    In regards to the original question, I've been using the empty constructor, and setting the fields I needed. (I'm in vb.net with .net 4.0, and it won't let me call New ToolStripMenuItem() since it has a MustInherit tag, so I made this class:

    Public Class DynamicToolStripMenuItem
        Inherits ToolStripMenuItem
    
        Public Sub New(value As Integer, text As String, handler As System.EventHandler)
            MyBase.New()
            Me.Text = text
            Me.Visible = True
            Me.Tag = value
            AddHandler Me.Click, handler
        End Sub
    End Class
    

提交回复
热议问题