2013-05-14 71 views
-2

有没有办法左对齐工具栏(不离开“空格”)的代码? enter image description here通过代码左对齐工具栏

(比如,点击该按钮2时) enter image description here

PS
此外这种情况

enter image description here
为 “左对齐” 是指:
enter image description here

+0

左对齐工具栏意味着你需要改变的MenuStrip类似的东西现在的位置? – 2013-05-14 10:22:54

+0

我需要从第一个图像的工具栏像第二个图像的工具栏一样对齐。 – serhio 2013-05-14 10:23:44

+0

就这样,我可以确定我已经理解了这个问题,是否当你停靠(DockStyle)时,你不能再应用一个宽度?因此,宽度比你想要的宽得多。 – Dave 2013-05-14 10:52:47

回答

0

更新

根据您的标准改变相当戏剧性,下面是一些代码,它会让你去。它不完美,甚至接近完美!

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     _otherStrips = new List<OtherStrips>(); 
    } 

    private int _currentHeight = 0; 
    private List<OtherStrips> _otherStrips; 

    private void button1_Click(object sender, EventArgs e) 
    { 
     foreach (var c in panel1.Controls) 
     { 
      if (c is ToolStrip) 
      { 
       ToolStrip ts = (ToolStrip)c; 
       _otherStrips.Add(new OtherStrips() { Top = ts.Top, Width = ts.Width, Name = ts.Name }); 
       MoveToPosition(ts); 
      } 
     } 
    } 

    private void MoveToPosition(ToolStrip toolStrip) 
    { 
     bool isInline; 
     toolStrip.Left = GetWidth(toolStrip, out isInline); 

     if (isInline) 
      toolStrip.Top = GetTop(toolStrip); 
    } 

    private int GetWidth(ToolStrip ts, out bool isInline) 
    { 
     int result = 0; 
     isInline = false; 
     foreach (var item in _otherStrips) 
     { 
      if (item.Name == ts.Name) 
       continue; 

      if (item.Top == ts.Top) 
      { 
       isInline = true; 
       break; 
      } 
     } 

     if (!isInline) 
      return result; 

     foreach (var item in _otherStrips) 
     { 
      if (item.Width == ts.Width) 
       result += item.Width; 
     } 

     return result + 22;//hack since the width is out by about 22pixels. Not going to spend any time fixing this 
    } 

    private int GetTop(ToolStrip ts) 
    { 
     foreach (var item in _otherStrips) 
     { 
      if (item.Name == ts.Name) 
       continue; 

      if (item.Top == ts.Top) 
       return item.Top; 
     } 

     _currentHeight += ts.Height; 
     return _currentHeight; 
    } 
} 

struct OtherStrips 
{ 
    public int Top { get; set; } 
    public int Width { get; set; } 
    public string Name { get; set; } 
} 
+0

看到我的编辑...还有,可能有不定数量的工具栏... – serhio 2013-05-14 12:08:11

+0

@serhio,我更新了我的答案。这是不完美的,但一个良好的开始 – Dave 2013-05-15 07:54:04

+0

是不是我采取的解决方案,但我将标记为答案... – serhio 2013-05-22 08:43:41

0

你可以用它来对准留下您的ToolStrip

toolStrip1.Location = new Point(0, toolStrip1.Location.Y); 
+0

通过替换名称使用toolStrip2和toolStrip3相同的代码..我测试过了,它的工作: ) – Jexfer 2013-05-14 11:15:23

+0

看到我的编辑,这不适用于可变数量的工具栏... – serhio 2013-05-14 12:09:40