我正在尝试使用 UI 自动化实现右键单击上下文菜单。由于 UI 自动化没有原生右键单击模式,我将 ExpandCollapse 提供程序添加到列表视图的 AutomationPeer 类,并将展开和折叠映射到打开和关闭上下文菜单。
我的问题是,有没有更好的方法来调用上下文菜单而不涉及尝试使用私有构造函数实例化一个类?我不能将 SendKeys 与 Shift-F10 一起使用。我想使用 PopupControlService 但它被标记为内部。
我糟糕的解决方法:
public class MyListViewAutomationPeer : ListViewAutomationPeer, IExpandCollapseProvider
{
public MyListViewAutomationPeer(MyListView owner)
: base(owner){}
public override object GetPattern(PatternInterface patternInterface)
{
if (patternInterface == PatternInterface.ExpandCollapse)
{
return this;
}
return base.GetPattern(patternInterface);
}
public void Expand()
{
MyListView owner = (MyListView)Owner;
//**********************
//Ouch!!! What a hack
//**********************
//ContextMenuEventArgs is a sealed class, with private constructors
//Instantiate it anyway ...
ContextMenuEventArgs cmea = (ContextMenuEventArgs)FormatterServices.GetUninitializedObject(typeof(ContextMenuEventArgs));
cmea.RoutedEvent = MyListView.ContextMenuOpeningEvent;
cmea.Source = owner;
//This will fire any developer code that is bound to the OpenContextMenuEvent
owner.RaiseEvent(cmea);
//The context menu didn't open because this is a hack, so force it open
owner.ContextMenu.Placement = PlacementMode.Center;
owner.ContextMenu.PlacementTarget = (UIElement)owner;
owner.ContextMenu.IsOpen = true;
}