4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WPFでTextBoxを含むDataTemplateをListViewの幅いっぱいに表示したい

Posted at

TR;DL

  • HorizontalContentAlignment="Stretch"
  • ScrollViewer.HorizontalScrollBarVisibility="Disabled"

このふたつの設定をする

ListViewの幅いっぱいにDataTemplateの中身を表示したい

ListViewだけもったWindowをテスト用に作成

<Window x:Class="TextboxInListSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TextboxInListSample"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="200"
        >
    <Grid x:Name="Grid">
        <ListView x:Name="List">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="1*"/>
                            <ColumnDefinition Width="5*"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Text="{Binding No}" Grid.Column="0"/>
                        <TextBox Text="{Binding Name}" Grid.Column="1"/>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

image.png
うーん。幅いっぱいにならない

HorizontalContentAlignment="Stretch" をつけると幅いっぱいになるらしい

        <ListView x:Name="List" HorizontalContentAlignment="Stretch">

image.png

おお、いいじゃん
テキストボックスの入力テストしてみよう

image.png

ちょっとまて
なんでテキストボックス伸びるん

最大幅は固定したい

試行錯誤

ListViewにMaxWidth設定すればいいのでは? → 効果なし

        <ListView x:Name="List" HorizontalContentAlignment="Stretch" MaxWidth="180">

ListView内のGridにMaxWidth設定すればいいのでは? → なんかずれた

                    <Grid MaxWidth="180">

image.png

ほんと不可解

ListView内のGridのWidthにListViewのActualWidthをBindingすればいいのでは? → なんか最初からはみでた

                    <Grid Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=ActualWidth}">

image.png

解決

ScrollViewer.HorizontalScrollBarVisibility="Disabled" が効果があるという記事を見つける

Stretching the items in a WPF ListView within a ViewBox - Stack Overflow

        <ListView x:Name="List" HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled">

image.png

できた!!!

でもなんでこれでそうなるのかよくわからない…

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?