Version: 2022.1
Relative and absolute positioning C# example
Best practices for managing elements

UQuery

You can use UQuery to retrieve elements from a visual tree. UQuery is based on JQuery or Linq, and is designed to limit dynamic memory allocation as much as possible. This allows for optimal performance on mobile platforms.

Retrieve elements

To use UQuery to retrieve elements, use the UQueryExtensions.Q or initialize a QueryBuilder with UQueryExtensions.Query.

例如,以下 UQuery 从根开始查找名为 foo 的第一个 Button

root.Query<Button>("foo").First();

以下 UQuery 在同一个组中名为 foo 的每个 Button 上进行迭代:

root.Query("foo").Children<Button>().ForEach(//执行操作);

最佳实践

Consider the following when you use UQuery:

  • UQuery traverses through the hierarchy to find elements by name, class or type. Cache results from UQuery at initialization.
  • If you need to retrieve multiple elements, use the QueryState struct (returned by the element.Query() method) and enumerate it to avoid creating lists. You can also construct a query once and execute it on different elements.
  • UI Toolkit doesn’t destroy visual elements that are no longer needed, it uses C# garbage collector to collect them. Be mindful to not accidentally retain references to visual elements in a class that outlives the UIDocuments or Window where the elements came from.
  • Capture VisualElement variables inside closures.
  • When you create or release lots of elements, enable incremental garbage collection to avoid garbage collector spikes.

其他资源

Relative and absolute positioning C# example
Best practices for managing elements