版本:2023.2+
此示例演示了如何创建自定义绑定以将 USS 选择器绑定到视觉元素。
此示例创建了一个自定义绑定,根据层级视图中子元素的顺序将 USS 类选择器分配给视觉元素的每个子元素。第一个元素始终具有左圆角边缘,而最后一个元素始终具有右圆角边缘。
可以在此 GitHub 代码仓库中找到此示例创建的完整文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发者。在开始之前,请熟悉以下内容:
创建一个自定义绑定类型,根据同级索引分配 USS 类。绑定仅在同级索引更改时才更新。
使用任何模板在 Unity 中创建项目。
在项目的 Assets 文件夹中,创建一个名为 AddMenuUSSClass.cs 的 C# 脚本,其中包含以下内容:
using UnityEngine.UIElements;
[UxmlObject]
public partial class AddMenuUssClass : CustomBinding
{
protected override BindingResult Update(in BindingContext context)
{
// Assign USS classes based on the sibling index. The binding updates when the sibling index changes.
var element = context.targetElement;
var index = element.parent.IndexOf(element);
element.EnableInClassList("menu-button--first", index == 0);
element.EnableInClassList("menu-button--last", index == element.parent.childCount - 1);
return new BindingResult(BindingStatus.Success);
}
}
一般来说,您可以创建一个绑定来绑定到元素的现有属性。出于演示目的,此示例将创建一个自定义绑定,绑定到元素中不存在的属性。必须使用 UXML 或 C# 来设置绑定以绑定到不存在的属性。此示例使用 UXML 设置绑定。
在项目的 Assets 文件夹中,创建一个名为 CustomBinding.uss 的 USS 文件,其中包含以下内容:
.menu-button {
flex-direction: row;
height: 64px;
align-items: center;
justify-content: center;
}
.menu-button--first {
border-top-left-radius: 15px;
border-bottom-left-radius: 15px;
border-left-width: 2px;
}
.menu-button--last {
border-top-right-radius: 15px;
border-bottom-right-radius: 15px;
border-right-width: 2px;
}
Button {
margin: 0px;
border-color: red;
}
在项目的 Assets 文件夹中,创建一个名为 CustomBinding.uxml 的 UXML 文件,其中包含以下内容:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="True">
<ui:VisualElement class="menu-button">
<ui:Button text="Bloub">
<Bindings>
<AddMenuUssClass property="add-menu-button-class" />
</Bindings>
</ui:Button>
<ui:Button text="Bip">
<Bindings>
<AddMenuUssClass property="add-menu-button-class" />
</Bindings>
</ui:Button>
<ui:Button text="Boop">
<Bindings>
<AddMenuUssClass property="add-menu-button-class" />
</Bindings>
</ui:Button>
</ui:VisualElement>
</ui:UXML>
双击 CustomBinding.uxml 文件可在__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary Builder 中打开该文件。
在 StyleSheet 面板中,选择 + > 添加现有 USS (Add Existing USS),然后选择 CustomBinding.uss 文件。
保存更改。
要测试绑定,请更改 UI Builder 中按钮元素的顺序,并观察 UI Builder 视口中的更改。
CustomBinding.uxml 文件可在 UI Builder 中打开该文件。