ListBox の 幅いっぱいにアイテムを表示させたい

#wpdev_jp #wp7dev_jp

簡単にできそうでできないのがコレ。

Listbox などでコンテンツをバインドして、ItemTemplate で配置デザイン。文字だけならうまくいくんだけど、背景色を付けるとおかしなことになる。

image

ソースコードはこんな感じ。DataTemplate の Grid の VerticalAlignment=”Stretch” としてもダメ。 でも、Width=400 みたいに固定したくない。

 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
  <Grid.Resources>
    <DataTemplate x:Key="ItemTemplate1">
      <Grid Margin="5" Background="Gray">
        <TextBlock Text="{Binding Property1}" Padding="20,0,10,0"/>
      </Grid>
    </DataTemplate>
  </Grid.Resources>
  <ListBox FontSize="48" ItemsSource="{Binding Collection}"
      ItemTemplate="{StaticResource ItemTemplate1}">         
  </ListBox>
         
</Grid>

そこで、ListBox.ItemContatContainerStyle に設定を使いする。早い話が、ListBox の中の Itemをいじるのではなく、Item側の設定から、Itemのコンテナになっている部分を幅いっぱいにするという事。

   <ListBox FontSize="48" ItemsSource="{Binding Collection}"
      ItemTemplate="{StaticResource ItemTemplate1}">
    <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
      </Style>
    </ListBox.ItemContainerStyle>                
  </ListBox>

こうすれば、結果はこの通り。ListBox のテンプレートは便利だが、理解するのも大変。ぜひ、UX-TVをご覧ください。

image

ではまた!