Hello,
I want to create a horizontal scroll view that I can bind array to. Something like this
/// <summary>
/// Element that can be bound to an array/list property
/// It creates a and binds each element to a <see cref="itemTemplate"/>
/// </summary>
public class Gallery : BindableElement
{
[CreateProperty]
public VisualTreeAsset itemTemplate { get; set; }
public override VisualElement contentContainer => _scrollView;
private readonly ScrollView _scrollView = new ScrollView();
// How to implement this logic?
private void OnBoundPropertyValueChange()
{
// Populate the scroll view
// For each item in the bound property list, instantiate the itemTemplate and add it to the scrollView
}
}
How can I implement a logic like that? I can’t use the ListView since it doesn’t support horizontal mode.
While you can’t use ListView, you can probably dig through it’s source code to find out: UnityCsReference/Modules/UIElements/Core/Controls/ListView.cs at master · Unity-Technologies/UnityCsReference · GitHub
Namely stuff happens when you assign to the itemSource
property. Just normal C# stuff of doing things via a property setter.
I already went through this rabbit hole, ListView
, BaseVerticalCollectionView
, CollectionViewController
…
I just don’t get it. That’s why I asked the question here – I would like to see the minimum code required to bind array property like that.
Are we talking editor or runtime binding?
There was a whole lot of chatter about it in this thread: Can you use the new UI Toolkit Data Binding on List Views?
TL;DR, there’s no simple built-in binding support for collections, and there’s multiple approaches depending on what you need. My personal approach would be to wrap your array in a custom collection-like object that expresses hooks for the visual element to listen to. Probably a situation where using the INotifyBindablePropertyChanged interface on said object is a good idea, so the control can bind itself to it with the trigger mode of OnSourceChanged and be informed when it changes.
This could be done invisibly by the custom control internally if preferred. In any case, not something that can be distilled in a minimum amount of code. Collection controls are about the most complicated controls you could make.