13

I want to be able to align buttons within a stack panel centrally. The number of buttons is dynamic and generated when the control is loaded. For example, if 1 button is generated then this button should be placed in the center of the control. If 5 buttons are displayed then all 5 should be horizontally aligned next 2 each other but central to the control.

An alternative approach would be to have the control dynamically resize based on its content so it would be wider with more buttons and then horizontally align the user control on the page but I'm not sure how to approach either solution?

Does anybody have any ideas?

4

2 に答える 2

24

これはうまくいくはずです。スタック パネルで [水平方向の配置] を設定し、ボタンを動的に追加する場合は、それぞれに margin プロパティ値を指定して、互いにある程度のスペースを確保してください。互いに水平で、コントロールの中心です。

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="20">
        <Button Margin="10">one</Button>
        <Button Margin="10">two</Button>
        <Button Margin="10">three</Button>
        <Button Margin="10">four</Button>
        <Button Margin="10">five</Button>            
    </StackPanel>
于 2012-06-22T14:00:09.667 に答える
8

XAMLで次のように簡単に設定できます

StackPanel.HorizontalAlignment = HorizontalAlignment.Center;

また

HorizontalAlignment="Center"(GrayFox374が言及したように)

これは、さまざまな配置操作を説明するMSDNのサンプルであり、必要なものが正確にあると思います- 方法:StackPanelのコンテンツを水平方向または垂直方向に整列させる方法

于 2012-06-22T14:06:42.710 に答える