Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5534

Vertical stretching for ListViewItems

I have a List view with many ListViewItems, but each ListViewItem could have one or more lines of text.

All i need is force each ListViewItem to stretch vertically as its own content.

Is it posible with ListView ?

There is another control allow me to do that?

enter image description here

Upvotes: 1

Views: 80

Answers (1)

Matt Wilkinson
Matt Wilkinson

Reputation: 590

If you are using MVVM and DataTemplates to produce the ListViewItems dynamically they are doing this by default. This is an quick example of this.

MainWindow.xaml

<ListView ItemsSource="{Binding items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Label Content="{Binding text}" />
                <ListView ItemsSource="{Binding strings}">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <Label Content="{Binding}" />
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

MainViewModel & ListItemViewModel

public class MainViewModel
{
    public List<ListItemViewModel> items { get; set; }
    public MainViewModel()
    {
        List<ListItemViewModel> things = new List<ListItemViewModel>();
        List<string> temp = new List<string>();
        for (int i = 0; i < 5; i++)
        {
            temp.Add(i + "");
            things.Add(new ListItemViewModel()
            {
                text = "item"+i,
                strings = temp.ToList<string>()
            });

        }
        items = things;
    }
}

public class ListItemViewModel
{
    public String text { get; set; }
    public List<string> strings { get; set; }

}

As stated below in the comments, this is a very quickly thrown together demo and the ViewModels do not contain any of the INotifyPropertyChanged events. The UI will not automatically reflect changes in the ViewModel because of this.

Upvotes: 1

Related Questions