Skip to main content
 首页 » 编程设计

c#之ToolStripDropDown 列表的水平分隔符

2024年02月20日12bluestorm

我正在创建一个包含三个 ToolStripButton 的 ToolStripDropDownButton。我想在第二个按钮之后添加一个分隔符。

这是我的代码。

using System; 
using System.Drawing; 
using System.Windows.Forms; 
 
namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
        internal ToolStripDropDownButton dropDownButton1; 
        internal ToolStripDropDown dropDown; 
        internal ToolStripButton buttonRed; 
        internal ToolStripButton buttonBlue; 
        internal ToolStripButton buttonYellow; 
 
        public Form1() 
        { 
            InitializeComponent(); 
 
            dropDownButton1 = new ToolStripDropDownButton(); 
            dropDown = new ToolStripDropDown(); 
            dropDownButton1.Text = "A"; 
 
            dropDownButton1.DropDown = dropDown; 
            dropDownButton1.DropDownDirection = ToolStripDropDownDirection.Right; 
            dropDownButton1.ShowDropDownArrow = false; 
 
            buttonRed = new ToolStripButton(); 
            buttonRed.ForeColor = Color.Red; 
            buttonRed.Text = "A"; 
 
            buttonBlue = new ToolStripButton(); 
            buttonBlue.ForeColor = Color.Blue; 
            buttonBlue.Text = "A"; 
 
            buttonYellow = new ToolStripButton(); 
            buttonYellow.ForeColor = Color.Yellow; 
            buttonYellow.Text = "A"; 
 
            ToolStripSeparator s = new ToolStripSeparator(); 
 
            dropDown.Items.AddRange(new ToolStripItem[] { buttonRed, buttonBlue, s, buttonYellow }); 
            toolStrip1.Items.Add(dropDownButton1); 
        } 
    } 
} 

问题是分隔符是垂直显示的。

如何让它水平显示?

请您参考如下方法:

您需要设置ToolStripDropDown 的LayoutStyle 属性。默认情况下它是 ToolStripLayoutStyle.Flow,但必须设置为 ToolStripLayoutStyle.VerticalStackWithOverflow。

或者,您也可以跳过创建和配置 ToolStripDropDown 实例并使用其 将 ToolStripItem 直接添加到您的 ToolStripDropDownButton DropDownItems 属性:

dropDownButton1.DropDownItems.AddRange( 
    new ToolStripItem[] { buttonRed, buttonBlue, s, buttonYellow });