GtkSharp中TextView.PopulatePopup修改现有菜单项正常但新增不显示
问题原因
- Gtk 体系下所有控件默认
Visible属性为false,你手动创建的SeparatorMenuItem和MenuItem没有显式触发显示逻辑 - 常规菜单栏添加子项后通常会调用父容器的
ShowAll()方法递归显示所有子控件,所以不需要单独处理;但TextView的PopulatePopup事件触发时,默认菜单的子项已经完成显示逻辑,后续新增的自定义项不会被自动触发显示
解决方案
有两种常用实现方式,选择任意一种即可:
方式1:创建菜单项时单独触发显示
修改GetPopupMenuItems方法,每个菜单项创建完成后调用Show()方法:
IEnumerable<MenuItem> GetPopupMenuItems() { var separator = new SeparatorMenuItem(); separator.Show(); yield return separator; var importMenuItem = new MenuItem("Import single value from text file"); importMenuItem.Activated += (object source, EventArgs args) => FileOperation(source as Window, true, false); importMenuItem.Show(); yield return importMenuItem; }
方式2:添加完所有自定义项后统一触发菜单所有子项显示
在PopulatePopup事件处理逻辑的末尾调用菜单的ShowAll()方法,该操作不会影响原有默认菜单项的状态:
_textBox.PopulatePopup += (object source, PopulatePopupArgs args) => { if (args.Popup is Menu menu) { (menu.Children[0] as MenuItem).Activated += (object src, EventArgs a) => { Setting.SetRaw("This happened"); }; foreach (var item in GetPopupMenuItems()) { menu.Add(item); } // 新增这行即可 menu.ShowAll(); } };
内容的提问来源于stack exchange,提问作者antlersoft
相关产品推荐
相关产品推荐

