【发布时间】:2019-06-08 23:10:07
【问题描述】:
我有一个ContextMenuStrip,它与ListView 紧密相连,由各种ToolStripMenuItem 和ToolStripSeparator 组合而成。
我希望这个上下文菜单隐藏/显示这些控件,具体取决于ListView 的当前状态(视图中没有项目,仅选择了 1 个项目,选择了超过 1 个项目)。
ListView 是 UserControl 的一部分,它通过应用程序级 VSTO 插件加载到 Ms Word 中。
目前,我的策略是依赖控件的.tag 属性,并在上下文菜单中为每个控件运行此属性的切换。
它看起来像这样:
Private Sub ContextMenuStrip_PopulatedItems_Opening(sender As Object, e As CancelEventArgs) Handles ContextMenuStrip_PopulatedItems.Opening
Dim ThisListView As ListView = ContextMenuStrip_PopulatedItems.SourceControl
For Each MyControl As ToolStripItem In ContextMenuStrip_PopulatedItems.Controls
MyControl.Visible = False
Select Case CType(MyControl.Tag, String)
Case "ShowAlways"
MyControl.Visible = True
Case "WhenSelection"
If ThisListView.FocusedItem IsNot Nothing AndAlso ThisListView.SelectedItems.Count > 0 Then
MyControl.Visible = True
End If
Case "WhenSingleSelection"
If ThisListView.FocusedItem IsNot Nothing AndAlso ThisListView.SelectedItems.Count = 1 Then
MyControl.Visible = True
End If
Case "WhenMultipleSelection"
If ThisListView.FocusedItem IsNot Nothing AndAlso ThisListView.SelectedItems.Count > 1 Then
MyControl.Visible = True
End If
Case Else
Throw New ApplicationException("The control tag property is not recognized.")
End Select
Next
End Sub
当我右键单击ListView 时,我收到以下错误消息:
System.InvalidCastException: '无法转换类型的对象 'StickyLabel' 输入 'System.Windows.Forms.ToolStripItem'。'
在线:For Each MyControl As ToolStripItem In ContextMenuStrip_FilesToPopulate.Control。
在搜索“StickyLabel”时,我没有在 Google 上找到任何文档或回复。而且我不明白为什么它试图在我的 ForeEach 循环中投射它,而不是跳过它?
【问题讨论】:
-
StickyLabel 是 ToolStripScrollButton 的 implementation detail。当您编写“应该适用于任何菜单项”代码时,不是您希望看到的内容,而是迭代 Items 属性。值得注意的是 ToolStrip 类如何成为 WPF 团队的训练轮。
-
是的,就像经常发生的那样,我被困了几个小时,但在问了 SO.. 上的问题几分钟后就想通了。
.Controls上的文档非常具有误导性(为什么它不是私有字段?) .不过感谢您的链接! -
“.Controls 上的文档非常具有误导性”。不。该属性的文档完全正确。它说“此属性与此类无关”。这有什么误导性?