2016-09-21 936 views
2

我正在使用Windows窗體並試圖在FlowLayoutPanel上添加多個單選按鈕。我可能會動態地添加10-12個單選按鈕,並可能會將它們刪除,但始終它們將位於FlowLayoutPanel的中心。目前它們被添加如下圖: enter image description here如何居中對齊FlowLayoutPanel中的多個單選按鈕?

+0

爲什麼要使用Flowlayoutpanel?你可以簡單地使用TableLayoutPanel並居中控制。 – MSL

+0

錨點屬性可能會幫助你。 (設置爲左右) –

+0

實際上,閱讀這個問題應該可以幫助你們兩個人。 – TaW

回答

3

要微調其容器中控件的位置,您可以修改它們的Margin屬性。

假設你有一個列表居中控制:

List<Control> ctls = new List<Control>(); 
foreach (Control c in flowLayoutPanel1.Controls) ctls.Add(c); 

你可以調用一個函數來將它們對齊:

void centerControls(List<Control> ctls, Control container) 
{ 
    int w = container.ClientSize.Width; 
    int marge = (w - ctls.Sum(x => x.Width))/2; 
    Padding oldM = ctls[0].Margin; 
    ctls.First().Margin = new Padding(marge, oldM.Top, oldM.Right, oldM.Bottom); 
    ctls.Last().Margin = new Padding(oldM.Left, oldM.Top, oldM.Right, marge); 
} 

enter image description here

enter image description here

調用每當你添加或刪除功能VED控制:

centerControls(ctls, flowLayoutPanel1); 

您需要重置當你添加新的按鈕Margins ..

請注意,我只更改外Margins,沒有之間的空間。對於後者,你可以計算出空間,並改變Margins所有控件:

enter image description here

void spaceControls(List<Control> ctls, Control container) 
{ 
    int w = container.ClientSize.Width; 
    int marge = (w - ctls.Sum(x => x.Width))/(ctls.Count * 2); 
    Padding oldM = ctls[0].Margin; 
    Padding newM = new Padding(marge, oldM.Top, marge, oldM.Bottom); 
    foreach (Control c in ctls) c.Margin = newM; 
} 

也不要想着當RadioButtons多行是必有發生什麼!您可能需要在maintinang清單中加入更多的努力..

還要注意,用戶不喜歡他們的控件跳過很多!

更新:確實有看看AR禮的帖子herehere的方式來實現類似的無代碼方式一號佈局!

+1

你可以在不編寫代碼的情況下實現這種佈局。如果您將一個自動調整大小的'FlowLayoutPanel'設置爲'Top'和'Bottom'在一個'TableLayoutPanel'中設置爲單個單元格,則添加到'FlowLayouPanel'的控件將始終與'TableLayouPanel'。這[post](https://stackoverflow.com/questions/38824530/how-to-set-flowlayout-button-to-center-of-form)包含實現這種佈局所需的設置。使用這樣的設置使得佈局更加可靠。 –

+1

帶有單個單元格的'TableLayoutPanel'的一個很好的特性是它可以幫助我們在中心垂直和水平地放置內容,而無需編寫如[本文]中提到的單行代碼(http://stackoverflow.com/a/39047133/3110834)。 –

+0

無論如何,你的代碼也在工作,但是OP應該小心邊距,並且當容器大小發生變化時他們應該應用這些方法。 –