LoginSignup
6
6

More than 5 years have passed since last update.

[WPF]*とAutoの違いをきちんと把握しておらずミスった話

Last updated at Posted at 2019-01-07

WPFで実装をしていて困ったので、備忘録としてあげておきます。
コントロールを配置したときに領域が思ったように確保されなくて困る時があります。
そういう場合、Gridの指定を見ると適切でない時があります。

幅205のMainWindowを用意し、Gridで*を指定してButtonを置くと、

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="abcdefghijklmnopqrstuvwxyz" Grid.Column="0" />
        <Button Content="Button" Grid.Column="1" Width="40"/>
    </Grid>

image.png
Buttonが必要以上に領域を確保してしまっています。

しかし、GridでAutoを指定してButtonを置くと、

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="abcdefghijklmnopqrstuvwxyz" Grid.Column="0" />
        <Button Content="Button" Grid.Column="1" Width="40"/>
    </Grid>

image.png
Buttonが必要なサイズのみ確保します。

*とAutoは何が違う?

*は「Gridに比例したサイズ」、Autoは「行列に配置されている内容の要素が必要とするサイズ」だけコントロールの領域を確保します。
上記の例を見ると、*の場合、行を1対1の比率で定義されているため幅40以上にButtonの領域を確保してしまっています。これは*が使用可能なスペースを指定した比率でコントロールを配置するためです。
Autoの場合は、Buttonの幅40だけを領域を確保しています。

戒め

Gridの指定が*で定義した箇所にコントロールを置いていることに気づかず、思った以上に領域が確保されて「なんでだろうコントロールの設定ミスったかな」とコントロールばかり見て中々気づけなかった経験があります。
そんなときはGridの指定が正しいか確認しましょう。

参考

https://stackoverflow.com/questions/3164651/what-is-the-different-between-auto-and-when-setting-width-height-for-a-gri
https://blog.okazuki.jp/entry/20130106/1357483477

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6