试图添加一个工具条的一ToolStripPanel side-by-side与现有的工具条
-
03-07-2019 - |
题
我使用。网2.0with Visual Studio2005年和我试图添加两个不同的toolstrips到顶部的形式,这样,它们显示side-by-side.我想它会喜欢的词2003年,在那里你可以增加多toolstrips的同行,他们显示在线彼,而不是致力于一个行为每个工具条.
所以我加了一个ToolStripPanel和停靠它的顶部的形式(我没有使用ToolStripContainer因为我不需要有额外的面板;我只是需要一个在上)。我加入这两个toolstrips和设置自己的弹性,以虚假的。我可以让他们显示在设计师的窗边,但是在运行时的ToolStripPanel分toolstrips并给出了每个工具条自己的专用行。如果雪上加霜的是,当我停止调试和返回设计师的设计,我发现,设计者是移动toolstrips到他们自己的行为很好!我做错了什么在这里?
我已经Google搜索所有一天发现了一些有关的信息ToolStripPanelRow对象,但是我没有看到一个简单的方法来增加toolstrips它(即它没有一个ToolStripPanelRow.控制。添加的方法或类似的东西),所有这已经是一个控制()财产,回返的一系列控制对象,并且我没有太多的运气,试图项目添加到那阵列。我还发现一些文件上的ToolStripPanel.参加方法,这听起来就像它应该做的工作,所以我尝试了所有3载但是他们不工作。无论我做什么,或者其选择我尝试,它总是增加了新的工具条的顶部的小组其自己的行和推动其他一切了下来。
在利益的充分披露我应该警告你,我有ToolStripPanel和一个toolstrips加入到一个基类的形式,并且我在努力加入其他工具条的一个子类的形式,继承基类的形式。该ToolStripPanel和工具条的baseclass的形式是宣布"受保护的朋友",所以这应该是工作。正如我所提到的,该子类形式的设计师的窗口会允许我这样做(至少一次)。
如果有人能帮助我得到这工作或者至少一些阐明为什么它不是,我将非常感激。
解决方案
我创建了一个自定义ToolStripPanel,以便我可以重载LayoutEngine;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Layout;
namespace CustomGUI
{
class CustomToolStripPanel : ToolStripPanel
{
private LayoutEngine _layoutEngine;
public override LayoutEngine LayoutEngine
{
get
{
if (_layoutEngine == null) _layoutEngine = new CustomLayoutEngine();
return _layoutEngine;
}
}
public override Size GetPreferredSize(Size proposedSize)
{
Size size = base.GetPreferredSize(proposedSize);
foreach(Control control in Controls)
{
int newHeight = control.Height + control.Margin.Vertical + Padding.Vertical;
if (newHeight > size.Height) size.Height = newHeight;
}
return size;
}
}
}
然后自定义LayoutEngine布局ToolStrips;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Layout;
namespace CustomGUI
{
class CustomLayoutEngine : LayoutEngine
{
public override bool Layout(object container, LayoutEventArgs layoutEventArgs)
{
Control parent = container as Control;
Rectangle parentDisplayRectangle = parent.DisplayRectangle;
Control [] source = new Control[parent.Controls.Count];
parent.Controls.CopyTo(source, 0);
Point nextControlLocation = parentDisplayRectangle.Location;
foreach (Control c in source)
{
if (!c.Visible) continue;
nextControlLocation.Offset(c.Margin.Left, c.Margin.Top);
c.Location = nextControlLocation;
if (c.AutoSize)
{
c.Size = c.GetPreferredSize(parentDisplayRectangle.Size);
}
nextControlLocation.Y = parentDisplayRectangle.Y;
nextControlLocation.X += c.Width + c.Margin.Right + parent.Padding.Horizontal;
}
return false;
}
}
}
需要一段时间的一件事是,更改一个ToolStrip项的位置/大小将导致布局重新触发,并重新排序控件。所以我在布局循环之前获取控件的副本。 并且您无法使用AddRange(...)将项目添加到自定义面板由于某种原因 - 需要一次添加(...)它们。
希望有所帮助(它基于 MSDN LayoutEngine示例,为ToolStripPanels修复了
Wyzfen
其他提示
System.Windows.Forms.FlowLayoutPanel可以完成这项工作。
只需按正确的顺序放入ToolStrip控件。
我认为在你的情况下,你可以逃脱,只有设置LayoutStyle在你的工具条,ToolStripLayoutStyle.HorizontalStackWithOverflow而不是需要自己的定义LayoutEngine.
我问一个 不同的问题 在一个类似的议题上如何处理布局的动态项目,以更好地控制的溢出。