How do I resize a list view to content?

So I created a list view and I want its size to adjust to its content. Seems simple enough but I can’t figure out how to do it.

If I set flex-grow to 1 then the list take the entire window.

If I set flex-grow to 0 then the list is completely shrieked and the content is not visible.

If I create a dummy element below the list view then the space is equally divided between the two.

How am I supposed to do it then?
Thanks.

On which item did you set the flex-grow to 0? When I try this sample, it seems to work as you would expect it to:

using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

public class ListViewExampleWindow : EditorWindow
{
    [MenuItem("Window/ListViewExampleWindow")]
    public static void OpenDemoManual()
    {
        GetWindow<ListViewExampleWindow>().Show();
    }

    public void OnEnable()
    {
        const int itemCount = 10;
        var items = new List<string>(itemCount);
        for (int i = 1; i <= itemCount; i++)
            items.Add(i.ToString());

        Func<VisualElement> makeItem = () => new Label();
        Action<VisualElement, int> bindItem = (e, i) => (e as Label).text = items[i];
        const int itemHeight = 16;
        var listView = new ListView(items, itemHeight, makeItem, bindItem);
        listView.style.flexGrow = 0;
        listView.style.borderLeftWidth = 2;
        listView.style.borderLeftColor = Color.red;
        rootVisualElement.Add(listView);

        rootVisualElement.Add(new VisualElement{
            style = {
                flexGrow = 1,
                backgroundColor = Color.green
            }
        });
    }
}

Thank you AlexandreT.
This is what your example looks like on Unity 2020.3.32.

Switching to 2022.1 fixes the issue.

1 Like

Interesting, thanks for letting us know, I’ll report the problem.