Version: 2022.1
LanguageEnglish
  • C#

ListView

class in UnityEngine.UIElements

/

Inherits from:UIElements.BaseListView

/

Implemented in:UnityEngine.UIElementsModule

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Description

A ListView is a vertically scrollable area that links to, and displays, a list of items.

A ListView is a ScrollView with additional logic to display a list of vertically-arranged VisualElements. Each VisualElement in the list is bound to a corresponding element in a data-source list. The data-source list can contain elements of any type.

The logic required to create VisualElements, and to bind them to or unbind them from the data source, varies depending on the intended result. For the ListView to function correctly, you must supply at least a value for itemsSource.

It's also recommended to supply the following properties for more complex items:
- makeItem
- bindItem
- fixedItemHeight when using CollectionVirtualizationMethod.FixedHeight


The ListView creates multiple VisualElement objects for the visible items. As the user scrolls, the ListView recycles these objects and re-binds them to new data items.

To set the height of a single item in pixels, set the item-height property in UXML or the ListView.itemHeight property in C# to the desired value.

To display a border around the scrollable area, set the show-border property in UXML or the ListView.showBorder property in C# to true.

By default, the user can select one element in the list at a time. To change the default selection use the selection-type property in UXML or theListView.selectionType property in C#. To allow the user to select more than one element simultaneously, set the property to Selection.Multiple. To prevent the user from selecting items, set the property to Selection.None.

By default, all rows in the ListView have same background color. To make the row background colors alternate, set the show-alternating-row-backgrounds property in UXML or the ListView.showAlternatingRowBackgrounds property in C# to AlternatingRowBackground.ContentOnly or AlternatingRowBackground.All. For details, see AlternatingRowBackground.

By default, the user can't reorder the list's elements. To allow the user to drag the elements to reorder them, set the reorderable property in UXML or the ListView.reorderable property in C# to true.

To make the first item in the ListView display the number of items in the list, set the show-bound-collection-size property in UXML or the ListView.showBoundCollectionSize to true. This is useful for debugging. By default, the ListView's scroller element only scrolls vertically.

To enable horizontal scrolling when the displayed element is wider than the visible area, set the horizontal-scrolling-enabled property in UXML or the ListView.horizontalScrollingEnabled to true.

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

public void OnEnable() { // Create a list of data. In this case, numbers from 1 to 1000. const int itemCount = 1000; var items = new List<string>(itemCount); for (int i = 1; i <= itemCount; i++) items.Add(i.ToString());

// The "makeItem" function is called when the // ListView needs more items to render. Func<VisualElement> makeItem = () => new Label();

// As the user scrolls through the list, the ListView object // recycles elements created by the "makeItem" function, // and invoke the "bindItem" callback to associate // the element with the matching data item (specified as an index in the list). Action<VisualElement, int> bindItem = (e, i) => (e as Label).text = items[i];

// Provide the list view with an explicit height for every row // so it can calculate how many items to actually display const int itemHeight = 16;

var listView = new ListView(items, itemHeight, makeItem, bindItem);

listView.selectionType = SelectionType.Multiple;

listView.onItemsChosen += objects => Debug.Log(objects); listView.onSelectionChange += objects => Debug.Log(objects);

listView.style.flexGrow = 1.0f;

rootVisualElement.Add(listView); } }

Properties

bindItem Callback for binding a data item to the visual element.
destroyItem Callback invoked when a VisualElement created via makeItem is no longer needed and will be destroyed.
makeItem Callback for constructing the VisualElement that is the template for each recycled and re-bound element in the list.
unbindItem Callback for unbinding a data item from the VisualElement.

Constructors

ListView Creates a ListView with all default properties. The ListView.itemSource must all be set for the ListView to function properly.

Inherited Members

Static Properties

arraySizeFieldUssClassName The USS class name for the size field of the ListView when foldout header is enabled.
emptyLabelUssClassName The USS class name for label displayed when ListView is empty.
foldoutHeaderUssClassName The USS class name for the foldout header of the ListView.
footerUssClassName The USS class name for the footer of the ListView.
itemUssClassName The USS class name of item elements in ListView elements.
listViewWithFooterUssClassName The USS class name for ListView when add/remove footer is enabled.
listViewWithHeaderUssClassName The USS class name for ListView when foldout header is enabled.
reorderableItemContainerUssClassName The USS class name for item container in reorderable animated ListView.
reorderableItemHandleBarUssClassName The USS class name for drag handle bar in reorderable animated ListView.
reorderableItemHandleUssClassName The USS class name for drag handle in reorderable animated ListView.
reorderableItemUssClassName The USS class name for item elements in reorderable animated ListView.
reorderableUssClassName The USS class name for reorderable animated ListView elements.
scrollViewWithFooterUssClassName The USS class name for scroll view when add/remove footer is enabled.
ussClassName The USS class name for ListView elements.
borderUssClassName The USS class name for BaseVerticalCollectionView elements with a border.
dragHoverBarUssClassName The USS class name of the drag hover bar.
itemAlternativeBackgroundUssClassName The USS class name for odd rows in the BaseVerticalCollectionView.
itemDragHoverUssClassName The USS class name applied to an item element on drag hover.
itemSelectedVariantUssClassName The USS class name of selected item elements in the BaseVerticalCollectionView.
itemUssClassName The USS class name of item elements in BaseVerticalCollectionView elements.
listScrollViewUssClassName The USS class name of the scroll view in the BaseVerticalCollectionView.
ussClassName The USS class name for BaseVerticalCollectionView elements.
disabledUssClassName USS class name of local disabled elements.

Properties

headerTitle This property controls the text of the foldout header when using showFoldoutHeader.
reorderMode This property controls the drag and drop mode for the list view.
showAddRemoveFooter This property controls whether a footer will be added to the list view.
showBoundCollectionSize This property controls whether the list view displays the collection size (number of items).
showFoldoutHeader This property controls whether the list view displays a header, in the form of a foldout that can be expanded or collapsed.
viewController The view controller for this view, cast as a BaseListViewController.
contentContainer Returns the content container for the BaseVerticalCollectionView. Because the BaseVerticalCollectionView control automatically manages its content, this always returns null.
fixedItemHeight The height of a single item in the list, in pixels.
horizontalScrollingEnabled This property controls whether the collection view shows a horizontal scroll bar when its content does not fit in the visible area.
itemsSource The data source for collection items.
reorderable Gets or sets a value that indicates whether the user can drag list items to reorder them.
selectedIndex Returns or sets the selected item's index in the data source. If multiple items are selected, returns the first selected item's index. If multiple items are provided, sets them all as selected.
selectedIndices Returns the indices of selected items in the data source. Always returns an enumerable, even if no item is selected, or a single item is selected.
selectedItem Returns the selected item from the data source. If multiple items are selected, returns the first selected item.
selectedItems Returns the selected items from the data source. Always returns an enumerable, even if no item is selected, or a single item is selected.
selectionType Controls the selection type.
showAlternatingRowBackgrounds This property controls whether the background colors of collection view rows alternate. Takes a value from the AlternatingRowBackground enum.
showBorder Enable this property to display a border around the collection view.
viewController The view controller for this view.
virtualizationMethod The virtualization method to use for this collection when a scroll bar is visible. Takes a value from the CollectionVirtualizationMethod enum.
binding Binding object that will be updated.
bindingPath Path of the target property to be bound.
canGrabFocus Return true if the element can be focused.
delegatesFocus Whether the element should delegate the focus to its children.
focusable True if the element can be focused.
focusController Return the focus controller for this element.
tabIndex An integer used to sort focusables in the focus ring. Must be greater than or equal to zero.
childCount Number of child elements in this object's contentContainer.
contentContainer child elements are added to this element, usually this
contentRect The rectangle of the content area of the element, in the local space of the element.
customStyle Returns the custom style properties accessor for this element.
enabledInHierarchy Returns true if the VisualElement is enabled in its own hierarchy.
enabledSelf Returns true if the VisualElement is enabled locally.
experimental Returns the UIElements experimental interfaces.
generateVisualContent Called when the VisualElement visual contents need to be (re)generated.
hierarchy Access to this element physical hierarchy
layout The position and size of the VisualElement relative to its parent, as computed by the layout system.
localBound AABB after applying the transform to the rect, but before applying the layout translation.
name The name of this VisualElement.
paddingRect The rectangle of the padding area of the element, in the local space of the element.
panel The panel onto which this VisualElement is attached.
parent The parent of this VisualElement.
pickingMode Determines if this element can be pick during mouseEvents or IPanel.Pick queries.
resolvedStyle Returns the VisualElement resolved style values.
schedule Retrieves this VisualElement's IVisualElementScheduler
style Reference to the style object of this element.
styleSheets Returns a VisualElementStyleSheetSet that manipulates style sheets attached to this element.
this[int] Retrieves the child element at a specific index.
tooltip Text to display inside an information box after the user hovers the element for a small amount of time.
transform Returns a transform object for this VisualElement. ITransform
usageHints A combination of hint values that specify high-level intended usage patterns for the VisualElement. This property can only be set when the VisualElement is not yet part of a Panel. Once part of a Panel, this property becomes effectively read-only, and attempts to change it will throw an exception. The specification of proper UsageHints drives the system to make better decisions on how to process or accelerate certain operations based on the anticipated usage pattern. Note that those hints do not affect behavioral or visual results, but only affect the overall performance of the panel and the elements within. It's advised to always consider specifying the proper UsageHints, but keep in mind that some UsageHints might be internally ignored under certain conditions (e.g. due to hardware limitations on the target platform).
userData This property can be used to associate application-specific user data with this VisualElement.
viewDataKey Used for view data persistence (ie. tree expanded states, scroll position, zoom level).
visible Indicates whether or not this element should be rendered.
visualTreeAssetSource Stores the asset reference, if the generated element is cloned from a VisualTreeAsset.
worldBound AABB after applying the world transform to rect.
worldTransform Returns a matrix that cumulates the following operations (in order): -Local Scaling -Local Rotation -Local Translation -Layout Translation -Parent worldTransform (recursive definition - consider identity when there is no parent)

Public Methods

SetViewController Assigns the view controller for this view and registers all events required for it to function properly.
AddToSelection Adds an item to the collection of selected items.
ClearSelection Deselects any selected items.
GetRootElementForId Gets the root element the specified TreeView item.
GetRootElementForIndex Gets the root element the specified collection view item.
Rebuild Clears the collection view, recreates all visible visual elements, and rebinds all items.
RefreshItem Rebinds a single item if it is currently visible in the collection view.
RefreshItems Rebinds all items currently visible.
RemoveFromSelection Removes an item from the collection of selected items.
ScrollTo Scrolls to a specific VisualElement.
ScrollToItem Scrolls to a specific item index and makes it visible.
ScrollToItemById Scrolls to a specific item id and makes it visible.
SetSelection Sets the currently selected item.
SetSelectionWithoutNotify Sets a collection of selected items without triggering a selection change callback.
SetViewController Assigns the view controller for this view and registers all events required for it to function properly.
HasBubbleUpHandlers Return true if event handlers for the event propagation BubbleUp phase have been attached on this object.
HasTrickleDownHandlers Returns true if event handlers, for the event propagation TrickleDown phase, are attached to this object.
RegisterCallback Adds an event handler to the instance. If the event handler has already been registered for the same phase (either TrickleDown or BubbleUp) then this method has no effect.
SendEvent Sends an event to the event handler.
UnregisterCallback Remove callback from the instance.
Blur Tell the element to release the focus.
Focus Attempt to give the focus to this element.
Add Add an element to this element's contentContainer
AddToClassList Adds a class to the class list of the element in order to assign styles from USS.
BringToFront Brings this element to the end of its parent children list. The element will be visually in front of any overlapping sibling elements.
Children Returns the elements from its contentContainer.
ClassListContains Searches for a class in the class list of this element.
Clear Remove all child elements from this element's contentContainer
ClearClassList Removes all classes from the class list of this element. AddToClassList
Contains Checks if this element is an ancestor of the specified child element.
ContainsPoint Checks if the specified point intersects with this VisualElement's layout.
ElementAt Retrieves the child element at a specific index.
EnableInClassList Enables or disables the class with the given name.
FindAncestorUserData Searches up the hierarchy of this VisualElement and retrieves stored userData, if any is found.
FindCommonAncestor Finds the lowest common ancestor between two VisualElements inside the VisualTree hierarchy.
GetClasses Retrieve the classes for this element.
GetFirstAncestorOfType Walks up the hierarchy, starting from this element's parent, and returns the first VisualElement of this type
GetFirstOfType Walks up the hierarchy, starting from this element, and returns the first VisualElement of this type
IndexOf Retrieves the child index of the specified VisualElement.
Insert Insert an element into this element's contentContainer
MarkDirtyRepaint Triggers a repaint of the VisualElement on the next frame.
PlaceBehind Places this element right before the sibling element in their parent children list. If the element and the sibling position overlap, the element will be visually behind of its sibling.
PlaceInFront Places this element right after the sibling element in their parent children list. If the element and the sibling position overlap, the element will be visually in front of its sibling.
Remove Removes this child from the hierarchy
RemoveAt Remove the child element located at this position from this element's contentContainer
RemoveFromClassList Removes a class from the class list of the element.
RemoveFromHierarchy Removes this element from its parent hierarchy.
SendEvent Sends an event to the event handler.
SendToBack Sends this element to the beginning of its parent children list. The element will be visually behind any overlapping sibling elements.
SetEnabled Changes the VisualElement enabled state. A disabled VisualElement does not receive most events.
Sort Reorders child elements from this VisualElement contentContainer.
ToggleInClassList Toggles between adding and removing the given class name from the class list.

Protected Methods

CreateViewController Creates the view controller for this view. Override this method in inheritors to change the controller type.
ExecuteDefaultAction Executes logic after the callbacks registered on the event target have executed, unless the event has been marked to prevent its default behaviour. EventBase{T}.PreventDefault.
ExecuteDefaultActionAtTarget Executes logic after the callbacks registered on the event target have executed, unless the event is marked to prevent its default behaviour. EventBase{T}.PreventDefault.

Events

itemsAdded This event is called for every item added to the itemsSource. Includes the item index.
itemsRemoved This event is called for every item added to the itemsSource. Includes the item index.
itemIndexChanged Called when an item is moved in the itemsSource.
itemsSourceChanged Called when the itemsSource is reassigned or changes size.
onItemChosen Callback triggered when a user double-clicks an item to activate it. This is different from selecting the item.
onItemsChosen Callback triggered when the user acts on a selection of one or more items, for example by double-clicking or pressing Enter.
onSelectedIndicesChange Callback triggered when the selection changes.
onSelectionChange Callback triggered when the selection changes.
onSelectionChanged Callback triggered when the selection changes.
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961