包含此页的版本:
不含此页的版本:
版本: 2021.3+
ListView 控件是创建列表的最有效方法。若要使用 ListView 绑定到列表,请将 ListView 的绑定路径设置为包含列表的属性的名称。
此示例演示如何使用 ListView 绑定到列表。
该示例创建了一个切换列表,并将该列表绑定到以下GameSwitch对象。
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:
创建一个GameSwitch对象和序列化对象,该对象的列表为GameSwitch对象作为属性。
使用任何模板创建 Unity 项目。
在您的项目窗口一个窗口,显示您的内容Assets文件夹(项目选项卡)更多信息
在术语表中查看,创建一个名为bind-to-list以存储您的所有文件。
创建名为GameSwitch.cs并将其内容替换为以下内容:
using System;
[Serializable]
public struct GameSwitch
{
public string name;
public bool enabled;
}
创建名为game_switch.uxml并将其内容替换为以下内容:
<UXML xmlns="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<Box style="flex-direction: row;">
<Toggle binding-path="enabled" />
<TextField binding-path="name" readonly="true" style="flex-grow: 1;"/>
</Box>
</UXML>
创建名为GameSwitchListAsset.cs并将其内容替换为以下内容:
using System.Collections.Generic;
using UnityEngine;
namespace UIToolkitExamples
{
[CreateAssetMenu(menuName = "UIToolkitExamples/GameSwitchList")]
public class GameSwitchListAsset : ScriptableObject
{
public List<GameSwitch> switches;
public void Reset()
{
switches = new()
{
new() { name = "Use Local Server", enabled = false },
new() { name = "Show Debug Menu", enabled = false },
new() { name = "Show FPS Counter", enabled = true },
};
}
public bool IsSwitchEnabled(string switchName) => switches.Find(s => s.name == switchName).enabled;
}
}
创建一个自定义编辑器,该编辑器可以创建具有切换列表的资产。将切换列表绑定到GameSwitch列表,方法是将binding-path属性设置为GameSwitch列表,即switches.
创建一个名为Editor.
在 Editor 文件夹中,创建一个名为GameSwitchListEditor.cs并将其内容替换为以下内容:
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
[CustomEditor(typeof(GameSwitchListAsset))]
public class GameSwitchListEditor : Editor
{
[SerializeField]
VisualTreeAsset m_ItemAsset;
[SerializeField]
VisualTreeAsset m_EditorAsset;
public override VisualElement CreateInspectorGUI()
{
var root = m_EditorAsset.CloneTree();
var listView = root.Q<ListView>();
listView.makeItem = m_ItemAsset.CloneTree;
return root;
}
}
}
创建名为game_switch_list_editor.uxml并将其内容替换为以下内容:
<UXML xmlns="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<ListView virtualization-method="DynamicHeight"
reorder-mode="Animated"
binding-path="switches"
show-add-remove-footer="true"
show-border="true"
show-foldout-header="true"
header-title="Switches"
/>
</UXML>
在“项目”窗口中,选择GameSwitchListEditor.cs。
将 game_switch.uxml 拖到 项目资产(Item Asset)检查器一个 Unity 窗口,显示有关当前选定游戏对象、资产或项目设置的信息,允许您检查和编辑值。更多信息
请参阅术语表.
将 game_switch_list_editor.uxml 拖到检查器中的编辑器资源中。
switches属性的GameSwitchListAsset对象更改。