Cal*_*leb 2 c# flow menustrip menuitem
我想让MenuStrip 上的某些按钮与 MenuStrip 的右侧对齐。例如,菜单条右侧的 Focus ON 和 Focus OFF:
如果我将 MenuStrip 的 LayoutStyle 设置为 StackWithOverFlow,我可以让它工作,但是如果窗口大小减小,菜单项会被裁剪:
LayoutStyle 设置为 StackWithOverFlow 的 MenuStrip
我如何才能使菜单项与设置为 Flow 的 MenuStrip LayoutStyle 向右对齐?这样,当表单大小减小时,菜单项会转到下一行?
另外,当 MenuStrip 为更多菜单项创建新行时,如何使其他控件向下推一点?
小智 6
为了右对齐某些菜单项,您需要将项的Alignment值设置为Right。但是,右对齐仅适用于StackWithOverflow布局样式。如果您使用Flow对齐样式,则项目将始终从左到右流动。
此外,当您在StackWithOverflow布局样式中右对齐项目时,项目从外向内流动,因此如果您的原始布局是1 2 3 4 5,那么您的右对齐项目将是1 2 3 <gap> 5 4。
您的问题的解决方案分为两部分:
跟踪SizeChanged事件,根据所有菜单项的宽度和窗口的可用宽度来确定是否需要Flow或StackWithOverflow。
如果您必须更改布局样式,请交换右对齐的项目,以便它们在任一布局样式中以正确的顺序出现。
private void Form1_SizeChanged(object sender, EventArgs e)
{
int width = 0;
// add up the width of all items in the menu strip
foreach (ToolStripItem item in menuStrip1.Items)
width += item.Width;
// get the current layout style
ToolStripLayoutStyle oldStyle = menuStrip1.LayoutStyle;
// determine the new layout style
ToolStripLayoutStyle newStyle = (width < this.ClientSize.Width)
? menuStrip1.LayoutStyle = ToolStripLayoutStyle.StackWithOverflow
: menuStrip1.LayoutStyle = ToolStripLayoutStyle.Flow;
// do we need to change layout styles?
if (oldStyle != newStyle)
{
// update the layout style
menuStrip1.LayoutStyle = newStyle;
// swap the last item with the second-to-last item
int last = menuStrip1.Items.Count - 1;
ToolStripItem item = menuStrip1.Items[last];
menuStrip1.Items.RemoveAt(last);
menuStrip1.Items.Insert(last - 1, item);
}
}
Run Code Online (Sandbox Code Playgroud)如果您有两个以上的项目,则必须更仔细地调整右对齐项目的交换过程。上面的代码只是交换它们,但如果您有三个或更多项目,则需要完全颠倒它们的顺序。
| 归档时间: |
|
| 查看次数: |
4022 次 |
| 最近记录: |