wpf 如何让堆栈面板调整大小以适合它堆叠的控件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35559863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:41:26  来源:igfitidea点击:

How do I get stackpanel to resize to fit the controls it's stacking?

wpfstackpanel

提问by Alan Baljeu

I'm making a toolbar. I want the width of the window to equal the total width of the buttons. StackPanel seems perfect for the job because it lines everything up, but it won't stretch.

我正在制作一个工具栏。我希望窗口的宽度等于按钮的总宽度。StackPanel 似乎非常适合这项工作,因为它把所有东西都排列起来,但它不会拉伸。

  <Window Width="auto">
     <StackPanel Orientation="Horizontal" Width="auto">
        <Button />
        <Button />
     </StackPanel>
  </Window>

How do I make this work?

我如何使这项工作?

回答by Alan Baljeu

I found a very simple solution! Almost everybody (I've been searching tons of pages) suggests switching control types or something much more complex, but in fact, it's much simpler:

我找到了一个非常简单的解决方案!几乎每个人(我一直在搜索大量页面)都建议切换控件类型或更复杂的东西,但实际上,它要简单得多:

<Window         SizeToContent="Width"

That's the only change required.

这是唯一需要的改变。

The source of this bit: https://stackoverflow.com/a/2317914/971583, the second-ranked answer to the problem, which seems to me the better one.

这篇文章的来源:https: //stackoverflow.com/a/2317914/971583,这个问题的第二个答案,在我看来是更好的答案。

回答by StepUp

You can make the width of the window to equal the total width of the buttons using a UniformGrid instead of a StackPanel.

您可以使用 UniformGrid 而不是 StackPanel 使窗口的宽度等于按钮的总宽度。

<UniformGrid Margin="10" Rows="1" HorizontalAlignment="Right"
            VerticalAlignment="Bottom">
    <Button Grid.Column="0" Content="No" FontSize="18" Margin="5" Padding="6,3"/>
    <Button Grid.Column="1" Content="Yes, Absolutely" Margin="5" Padding="6,3"/>
    <Button Grid.Column="2" Content="Maybe" Margin="5" Padding="6,3"/>
</UniformGrid>

The UniformGrid provides eacg cell is the same height and the same width. This is what you want as you then avoid having to set the button sizes manually.

UniformGrid 规定每个单元格高度相同,宽度相同。这就是您想要的,因为您可以避免手动设置按钮大小。

Update:

更新:

I would suggest not to use Stackpanel. Even if you make the Stackpanel fill its parent, its children still "stacks" and won't fill the Stackpanel.

我建议不要使用 Stackpanel。即使您让 Stackpanel 填充其父项,其子项仍然“堆叠”并且不会填充 Stackpanel。

回答by Jonathan LEI

Use a Grid with Columns instead.

改为使用带有列的网格。

<Grid HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button />
    <Button Grid.Column="1" />
    <Button Grid.Column="2" />
    <Button Grid.Column="3" />
</Grid>