这就是我用来重置我的属性的方法
public static void InitResetContextMenuStrip(this PropertyGrid grid, params string[] resettableProperties)
{
if (grid.ContextMenuStrip != null)
return;
var menuStrip = new ContextMenuStrip();
var resetItem = new ToolStripMenuItem("Reset");
resetItem.Click += (s, e) =>
{
try
{
if (resettableProperties.Any(p => grid.SelectedGridItem.PropertyDescriptor.Name == p))
{
grid.SelectedGridItem.PropertyDescriptor.SetValue(grid.SelectedObject, null);
grid.Refresh(); //redraw the grid to reflect the changes
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
};
menuStrip.Items.Add(resetItem);
menuStrip.Opening += (s, e) =>
{
try
{
resetItem.Enabled = resettableProperties.Any(p => grid.SelectedGridItem.PropertyDescriptor.Name == p);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
};
grid.ContextMenuStrip = menuStrip;
}
这就是我使用它的方式:
myGrid.InitResetContextMenuStrip(
nameof(ClassName.PropertyName1),
nameof(ClassName.PropertyName2));
信用: http: //www.windows-tech.info/3/41955b2a405bf481.php