有一个ISelectionService
帮助获取或设置选定的组件,并在选择更改时通知。
您可以通过处理服务的事件来实现所需的行为,SelectionChanged
如下所示:
private void SelectionSVC_SelectionChanged(object sender, EventArgs e)
{
var selectionSVC = sender as ISelectionService;
if (selectionSVC == null) return;
try
{
selectionSVC.SelectionChanged -= SelectionSVC_SelectionChanged;
if ((Control.ModifierKeys & (Keys.Shift | Keys.Control)) > Keys.None)
{
var selection = selectionSVC.GetSelectedComponents()
.Cast<object>().LastOrDefault();
if (selection != null)
selectionSVC.SetSelectedComponents(new[] { selection },
SelectionTypes.Primary | SelectionTypes.Add);
}
}
finally
{
selectionSVC.SelectionChanged += SelectionSVC_SelectionChanged;
}
}
获取服务实例取决于上下文。例如在设计器窗口中使用 VS 包,具有以下实例IdesignerHost
:
var selectionSVC = (ISelectionService)host.GetService(typeof(ISelectionService));
if (selectionSVC != null)
selectionSVC.SelectionChanged += SelectionSVC_SelectionChanged;