在 ToolStripDropDownMenu 中隐藏 ImageMargin 和 CheckMargin

发布于 2024-10-10 01:33:41 字数 714 浏览 0 评论 0原文

我试图在某个 ToolStrip 内的每个 ToolSTripDropDownMenu 中设置 ImageMargin 和 CheckMargin 属性。

foreach (ToolStripDropDownButton tsd in toolStrip1.Items)
{
    ((ToolStripDropDownMenu)tsd.DropDown).ShowImageMargin = false;
    ((ToolStripDropDownMenu)tsd.DropDown).ShowCheckMargin = false;
}

抛出异常,内容如下:

System.InvalidCastException:无法将“System.Windows.Forms.ToolStripButton”类型的对象转换为“System.Windows.Forms.ToolStripDropDownButton”类型。

ToolStrip 包含除 ToolStripDropDownButtons 之外的控件(即 ToolStripButtons 和 ToolStripLabels),因此我可以看到错误发生的位置。我无法理解的是如何仅修改 ToolStripDropDownButtons。与标准 ContextMenu 不同,ToolStripDropDownMenu 默认情况下不包含 CheckMargin 或 ImageMargin 属性。

I'm trying to set the ImageMargin and CheckMargin properties in every ToolSTripDropDownMenu within a certain ToolStrip.

foreach (ToolStripDropDownButton tsd in toolStrip1.Items)
{
    ((ToolStripDropDownMenu)tsd.DropDown).ShowImageMargin = false;
    ((ToolStripDropDownMenu)tsd.DropDown).ShowCheckMargin = false;
}

An exception is thrown saying the following:

System.InvalidCastException: Unable to cast object of type 'System.Windows.Forms.ToolStripButton' to type 'System.Windows.Forms.ToolStripDropDownButton'.

The ToolStrip contains controls besides ToolStripDropDownButtons (namely ToolStripButtons and ToolStripLabels) so I can see where the error is occuring. What I can't wrap my head around is how to modify ONLY the ToolStripDropDownButtons. ToolStripDropDownMenu doesn't contain a CheckMargin or ImageMargin property by default unlike a standard ContextMenu.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自此以后,行同陌路 2024-10-17 01:33:41

foreach 语句不执行任何过滤,因此当您将项目类型声明为 ToolStripDropDownButton 时,它会尝试将序列中的每个项目转换为该类型类型。由于这对于某些项目是不可能的,因此您需要声明一个不太具体的类型并检查您想要的实例:

foreach (ToolStripItem tsi in toolStrip1.Items)
{
    if (tsi is ToolStripDropDownButton) {
        ToolStripDropDownButton tsd = (ToolStripDropDownButton)tsi;
        ((ToolStripDropDownMenu)tsd.DropDown).ShowImageMargin = false;
        ((ToolStripDropDownMenu)tsd.DropDown).ShowCheckMargin = false;
    }
}

The foreach statement doesn't perform any filtering, so when you declare the item type to be ToolStripDropDownButton as you have, it will attempt to cast every item in the sequence to that type. Since that's not possible for some of the items, you need to declare a less specific type and check for the instances you want:

foreach (ToolStripItem tsi in toolStrip1.Items)
{
    if (tsi is ToolStripDropDownButton) {
        ToolStripDropDownButton tsd = (ToolStripDropDownButton)tsi;
        ((ToolStripDropDownMenu)tsd.DropDown).ShowImageMargin = false;
        ((ToolStripDropDownMenu)tsd.DropDown).ShowCheckMargin = false;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文