【发布时间】:2011-12-25 21:46:15
【问题描述】:
是否可以在 WP7 中为 WebBrowser 添加上下文菜单?(如 IE)
silverlight 工具包上下文菜单不支持 WebBrowser!!!
【问题讨论】:
标签: c# silverlight windows-phone-7 silverlight-toolkit
是否可以在 WP7 中为 WebBrowser 添加上下文菜单?(如 IE)
silverlight 工具包上下文菜单不支持 WebBrowser!!!
【问题讨论】:
标签: c# silverlight windows-phone-7 silverlight-toolkit
WebBrowser 不支持上下文菜单,并且与其他 Silverlight 控件的功能不同。因此,无法直接添加 ContextMenu。但是,有一些可能的解决方法。其中之一是使用 InvokeScript 方法。你应该阅读this thread。显然线程底部的代码有效。
注意:GINternet 是 WebBrowser 控件的名称,因此您需要将其更改为您的。
public void AttachContextMenu()
{
try
{
if (GINternet.IsScriptEnabled)
{
GINternet.InvokeScript("execScript", "function FindParentLink(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'a') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentLink(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction FindParentImage(item) \r\n{\r\n\tif (!item.parentNode)\r\n\t\treturn null;\r\n\tif (item.tagName.toLowerCase() == 'img') \r\n\t{\r\n\t\treturn item;\r\n\t} \r\n\telse \r\n\t{\r\n\t\treturn FindParentImage(item.parentNode);\r\n\t}\r\n}\r\n\r\nfunction HandleContextMenu() \r\n{\r\n\tvar linkItem = FindParentLink(event.srcElement);\r\n var imageItem = FindParentImage(event.srcElement);\r\n var notifyOutput = '';\r\n if (linkItem != null) if (linkItem.href != null) notifyOutput += linkItem.href;\r\n if (imageItem != null) if (imageItem.src != null) notifyOutput += imageItem.src;\r\n if (notifyOutput != '')\r\n window.external.notify(notifyOutput);\r\n else\r\n\t\twindow.external.notify('NOTLINKIMG');\r\n}");
GINternet.InvokeScript("execScript", "document.oncontextmenu = HandleContextMenu;");
}
}
catch
{
}
}
【讨论】:
<phone:WebBrowser Name="webBrowser1"> <toolkit:ContextMenuService.ContextMenu> <toolkit:ContextMenu x:Name="menu1"> <toolkit:MenuItem Header="item1" /> </toolkit:ContextMenu> </toolkit:ContextMenuService.ContextMenu> </phone:WebBrowser> 并且上下文菜单显示在页面顶部!!!