UI 工具包中内置了以下标准控件:
上下文菜单根据上下文向用户显示一组选项或操作。此上下文可以指代任何事物,通常是指当前选择对象。
要启用上下文菜单,请将 ContextualMenuManipulator
操控器添加到视觉元素。此操控器会在发生鼠标右键按下事件或菜单键松开事件后显示上下文菜单。ContextualMenuManipulator
操控器还会添加一个对应于 ContextualMenuPopulateEvent
的回调。以下代码示例展示了如何执行此操作:
void InstallManipulator(VisualElement element)
{
ContextualMenuManipulator m = new ContextualMenuManipulator(MyDelegate);
m.target = element;
}
void MyDelegate(ContextualMenuPopulateEvent event)
{
// 修改 event.menu
event.menu.AppendAction("Properties", DisplayProperties, DropdownMenu.MenuAction.AlwaysEnabled);
}
void DisplayProperties(DropdownMenu.MenuAction menuItem)
{
// ...
}
提供给 ContextualMenuManipulator
构造函数的回调在最后调用,以便子元素可以填充菜单。
在内部,操控器会发送一个 ContextualMenuPopulateEvent
事件,此事件沿以下传播路径传播到目标元素层级视图:从视觉树的根到事件目标,再退回到视觉树的根。沿着传播路径,具有 ContextualMenuPopulateEvent
事件回调的元素可以在上下文菜单中添加、删除或修改菜单项。
一个元素收到 ContextualMenuPopulateEvent
时会通过调用 DropdownMenu.InsertAction()
或 DropdownMenu.AppendAction()
将菜单项添加到上下文菜单中。
这些函数中的每一个函数都采用两个回调作为参数。用户在菜单中选择菜单项时执行第一个回调。第二个回调在显示菜单之前执行,还会检查菜单项是否已启用。
两个回调都接收一个 MenuAction
作为参数。MenuAction
代表菜单项,具有以下其他有用的属性:
MenuAction.userData
会引用可能已用于 AppendAction()
或 InsertAction()
的用户数据。MenuAction.eventInfo
包含触发上下文菜单显示的事件的
相关信息。应在响应事件的操作中使用 MenuAction.eventInfo
。例如,可以使用鼠标位置根据所选的上下文菜单项创建和放置对象。Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.