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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24612964/
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 12:05:33  来源:igfitidea点击:

Set Button Size to Content Size in WPF Application

wpf

提问by john doe

I have the following code in WPF XAML:

我在 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>

I have set the width and height of the Button to "Auto" but still it stretches the complete horizontal width. What am I doing wrong? I do not want to provide a hardcoded values for the width and height!

我已将按钮的宽度和高度设置为“自动”,但它仍然会拉伸整个水平宽度。我究竟做错了什么?我不想为宽度和高度提供硬编码值!

回答by Sheridan

You are using the wrong kind of container control. The StackPaneldoes notresize its contents. Try a Gridinstead:

您正在使用错误类型的容器控件。该StackPanel不会调整其内容。尝试一个Grid

<Grid>
    <Button Content="Hello" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

Also, you don't need to set the Widthand Heightto "Auto", as the default values will enable the Buttonto stretch to fill its parent container (depending on the container control). Please see the Panels Overviewpage on MSDN for more help with the differences between the various container controls in WPF.

此外,您不需要将Widthand设置Height"Auto",因为默认值将使Buttonto 拉伸以填充其父容器(取决于容器控件)。有关 WPF 中各种容器控件之间差异的更多帮助,请参阅MSDN 上的面板概述页面。

回答by Golvellius

As Sheridan said, you do not need to set Width and Height to "Auto". Your problem is that the default alignment of the StackPanel content is "Stretch". So just set the HorizontalAlignment property of your button to "Left" or "Right".

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

回答by Guilherme Duarte

<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">
    <Grid>
        <Button Content="Hello World" Width="Auto" Height="Auto"></Button>
    </Grid>
</Window>