如果我猜对了,那么你想做的是if(userHasSomePermission) { CreateComponent };,而不是之前创建它,如果用户没有权限禁用/隐藏它
如果是这样的话,这不是科学,但有点棘手。
在您的 Form 构造函数中,您有 InitializeComponents() 方法,该方法存储在您的 Form.Designer.cs 文件中。在该文件中,您正在创建控件。
您可以做的是在您的 Form.cs 中创建更多方法,例如
private void CreatePanel1()
{
Panel p = new Panel();
p.Location = new Point(3, 3);
p.Size = new Size(50, 50);
p.BackgroundColor = Color.Black;
this.Controls.Add(p);
}
然后根据需要在构造函数中调用它:
public Form()
{
InitializeComponents();
if( checkIfUserHavePermission )
CreatePanel1();
}
这样,我们方法中的组件只会在需要时创建。
其中一个棘手的部分是you will not see components inside designer window,因为只有位于Form.Designer.cs/InitializeComponents() 中的组件才会在其中绘制。因此,您想要进行的任何更改都需要通过代码手动完成。
否则,如果您担心安全性并且不想只是隐藏/禁用某些控件,则可以在需要时将其删除。
因此,您可以使用每个控件的 Tag 属性,并将假设为 Admin_C 添加到每个控件的 Tag,这仅适用于管理员,然后执行以下操作:
public Form()
{
InitializeComponents();
if(userIsNotAdmin)
{
foreach (Control item in this.Controls)
{
if(item.Tag.ToString() == "Admin_C")
this.Controls.Remove(item);
}
}
}