Tống Việt Dũng
Tống Việt Dũng

Reputation: 75

ColumnDefinition in ListView DataTemplate does not expand to full width

I'm creating a ListView with DataTemplate is a only text and a button. I want the button to be right most side and text is to left most side. However I noticed that it seems like my Grid.ColumnDefinitions not take all the space of the ListViewItem (Or I thought so). I want them to expand to full width.

<ListView Padding="5" x:Name="RecipeList" FontSize="15">
   <ListView.ItemTemplate>
      <DataTemplate>
         <Grid>
            <Grid.ColumnDefinitions>
               <ColumnDefinition></ColumnDefinition>
               <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
                                
            <TextBlock Text="{Binding Name}" Grid.Column="0"/>
            <Button Grid.Column="1">Delete</Button>
         </Grid>
      </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

Result

Upvotes: 0

Views: 871

Answers (1)

thatguy
thatguy

Reputation: 22079

The default content alignment for a ListViewItem (the container of the content which is defined by your data template) is Left, so the Grid will only take as much space as it needs, but does not scale to the available width. Change it to Stretch is an item container style instead.

<ListView Padding="5" x:Name="RecipeList" FontSize="15">
   <ListView.ItemContainerStyle>
      <Style TargetType="{x:Type ListViewItem}">
         <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
      </Style>
   </ListView.ItemContainerStyle>
   <ListView.ItemTemplate>
      <DataTemplate>
         <Grid>
            <Grid.ColumnDefinitions>
               <ColumnDefinition></ColumnDefinition>
               <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
                                
            <TextBlock Text="{Binding Name}" Grid.Column="0"/>
            <Button Grid.Column="1">Delete</Button>
         </Grid>
      </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

Your columns are defined that the TextBlock and the Button take equal proportions in the grid. If you want to align the Button to the right and the TextBlock to take the remaining space, set the Width of the second column to Auto. Then the Button only uses as much space as it needs.

<Grid>
   <Grid.ColumnDefinitions>
      <ColumnDefinition></ColumnDefinition>
      <ColumnDefinition Width="Auto"/>
   </Grid.ColumnDefinitions>

   <TextBlock Text="{Binding Name}" Grid.Column="0"/>
   <Button Grid.Column="1">Delete</Button>
</Grid>

Upvotes: 2

Related Questions