1

我有一组内容动态变化的 Windows 窗体按钮。我想将它们保存在一个大小相同的数组中,并且所有按钮都自动调整大小以保持彼此相同的大小,并且对于具有最大内容的按钮来说足够大,如果这有意义的话。最好的方法是什么?

4

2 回答 2

2

首先将所有按钮设置为 AutoSize:

foreach (Button B in MyButtonArray)
{
    B.AutoSize = true;
}

然后设置所有内容:

foreach (Button B in MyButtonArray)
{
    B.Text = whatervercontent;
}

然后得到最大的按钮:

int MaxWidth = 0;
foreach (Button B in MyButtonArray)
{
    if (B.Width > MaxWidth) 
        MaxWidth = B.Width;
}

然后设置宽度,关闭 Autosize:

foreach (Button B in MyButtonArray)
{
    B.AutoSize = false;
    B.Width = MaxWidth;
}
于 2013-07-16T20:49:24.960 回答
1

您可以利用event而不是像这样循环遍历您的按钮数组:

public class Form1 : Form {
   public Form1(){
      InitializeComponent();
      //I suppose buttons is your buttons array defined somewhere.
      int m = 0;
      foreach (Button button in buttons)
        {
            Binding bind = new Binding("Width", this, "ButtonMaxWidth");
            bind.DataSourceUpdateMode = DataSourceUpdateMode.Never;//This is important
            button.DataBindings.Add(bind);        
            button.AutoSize = true;     
            if(button.Width > m) m = button.Width;
            button.SizeChanged += (s, e) =>
            {
                Button but = s as Button;
                if (but.Width > ButtonMaxWidth)
                {
                    but.DataBindings["Width"].WriteValue();
                } else but.Width = ButtonMaxWidth;
            };
        }
        ButtonMaxWidth = m;//Initialize the max width, this is done only once and you don't have to loop through your buttons to update the max width because it's done via the mechanism of `Binding` and `event`.
        //Try changing the Width of any button in your buttons array
        buttons[2].Width = 300;//if this > MaxWidth, all the buttons will change its Width to the new same MaxWidth, otherwise they will stay on the current MaxWidth.            
        //Try changing the Text of one of your buttons
        buttons[1].Text = "I love Windows Presentation Foundation";
   }
   public int ButtonMaxWidth {get;set;}
}
于 2013-07-17T04:03:39.233 回答