在WPF应用程序中将按钮大小设置为内容大小

joh*_*doe 12 wpf

我在WPF XAML中有以下代码:

<Window x:Class="WPFDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <StackPanel>
        <Button Content="Hello World" Width="Auto" Height="Auto"></Button>
    </StackPanel>


</Window>
Run Code Online (Sandbox Code Playgroud)

我已将Button的宽度和高度设置为"Auto",但仍然会拉伸整个水平宽度.我究竟做错了什么?我不想为宽度和高度提供硬编码值!

She*_*dan 17

您正在使用错误的容器控件.该StackPanel不会调整其内容.尝试Grid改为:

<Grid>
    <Button Content="Hello" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

此外,您不需要设置WidthHeight"Auto",作为默认值将使Button伸展,以填补它的父容器(依赖于容器控件).有关WPF中各种容器控件之间差异的更多帮助,请参阅MSDN上的" 面板概述"页面.

  • 我试图将Button放在网格中,但现在Button取整个屏幕而不是内容的大小.看起来我必须将网格划分为行和列. (2认同)
  • 将“ Horizo​​ntalAlignment”和“ VerticalAlignment”设置为“ Center”,按钮将适合其内容。 (2认同)

Gol*_*ius 5

正如谢里丹所说,您不需要将宽度和高度设置为“自动”。您的问题是 StackPanel 内容的默认对齐方式是“Stretch”。因此,只需将按钮的 Horizo​​ntalAlignment 属性设置为“左”或“右”。