接下来的步骤是实现能在PropertyGrid中随意修改任何控件的属性。只要为DesignSurface的SelectionService实现一个SelectionChanged事件就行了。切换到Form1的代码窗口,为窗体类添加一个私有成员:
private ISelectionService selectionService;
然后再Load事件的最后加上:
selectionService = surface.GetService(typeof(ISelectionService)) as ISelectionService;
selectionService.SelectionChanged += new EventHandler(selectionService_SelectionChanged);
当然也为窗体类加上以下事件方法:
void selectionService_SelectionChanged(object sender, EventArgs e)
{
object[] selection;
if (selectionService.SelectionCount == 0)
propertyGrid1.SelectedObject = null;
else
{
selection = new object[selectionService.SelectionCount];
selectionService.GetSelectedComponents().CopyTo(selection, 0);
propertyGrid1.SelectedObjects = selection;
}
}
以下是运行时的界面: