1

ボタンが付いたWPFウィンドウがあります。テキストに応じてボタンの幅を増減させたい。これどうやってするの?

4

2 に答える 2

3

Widthプロパティを に設定しAuto、Horizo​​ntalAlignment ( CenterRightまたは) を指定するだけです。これは、Leftデフォルト値が であるためです。これにより、コンテナーが塗りつぶされます。Stretch

これがどのように機能するかの例を次に示します。

コード

<Window x:Class="StackOverflow.WPF.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">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Button Content="A Default Button"/>
        <Button Content="An Auto Width Button" 
                Width="Auto" 
                HorizontalAlignment="Center" 
                Grid.Column="1"/>
        <Button Content="An Auto Width and Height Button" 
                Width="Auto" Height="Auto" 
                HorizontalAlignment="Center" 
                VerticalAlignment="Center" 
                Grid.Column="0" Grid.Row="1"/>
    </Grid>
</Window>

出力

ここに画像の説明を入力

于 2013-03-27T13:06:00.910 に答える
2

ボタンに固定幅を設定しないと、ボタンの幅がコンテンツに合わせて調整されます。

于 2013-03-27T13:09:46.740 に答える