Ashot Khachatryan Ashot Khachatryan - 2 months ago 23
C# Question

Fill ListView items in WPF

It seems to work for everyone but not for me. I want to fill ListView items horizontally when my window is bigger then stack panel with items. I have the following .xaml

<ListView x:Name="comboBox" ItemsSource="{Binding ArticleCategories}" SelectedItem="{Binding SelectedArticleCategory}" HorizontalAlignment="Stretch" Margin="0,0,0,0" Background="Azure" VerticalAlignment="Top">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" ></Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Button Content="abc" Width="Auto"></Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>


Here is what I have
enter image description here

Answer

You may use a UniformGrid with a single row as ItemsPanel:

<ListView ...>
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Button Content="abc"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
Comments