Hey all! I’m breaking my head on how to do something that I thought would be pretty easy! (insert sweating emoji)
I have a ListView that is meant to display a property that is a List<> and the inner element is a struct (not super important). The list binds fine, and the comments display.
This is what they look like:
Now, I want to assign a method to that little Trash button. How do I do that?
The challenge seems to lie in the fact that elements of the list are not available at the moment the Inspector is constructed, so I tried to use GeometryChangedEvent
on the list, and it’s just thrown a bunch of times… so I ended up going for the list’s bindItem
method.
This works, I hook into that:
_commentsList.bindItem += OnBindCommentItem;
_commentsList.unbindItem += OnUnbindCommentItem;
private void OnBindCommentItem(VisualElement element, int i)
{
PropertyField propField = (PropertyField)element;
propField.BindProperty(_commentsProperty.GetArrayElementAtIndex(i));
propField.userData = i;
propField.RegisterCallback<GeometryChangedEvent>(OnCommentReady);
}
private void OnUnbindCommentItem(VisualElement element, int i)
{
PropertyField propField = (PropertyField)element;
propField.Unbind();
propField.UnregisterCallback<GeometryChangedEvent>(OnCommentReady);
}
private void OnCommentReady(GeometryChangedEvent evt)
{
((PropertyField)evt.target).UnregisterCallback<GeometryChangedEvent>(OnCommentReady);
VisualElement comment = (VisualElement)evt.target;
int index = (int)comment.userData;
comment.Q<Button>("DeleteCommentBtn").clicked += () => RemoveComment(index);
Debug.Log($"Comment {index} ready");
}
This all works fine the first time. It also works for newly-added elements, because OnBindCommentItem
is called, so once the GeometryChangedEvent
is fired, the button receives its callback.
However, if click one of the trash buttons, and one element is removed from the list, the listview rebuilds (as I would expect) and elements are rebinded, but it seems like GeometryChangedEvent
s are not fired, because perhaps the elements don’t change shape/size/position?
How am I supposed to know when the element is ready then, to be able to reliably add the button callback?
Thanks for any help.