2013-02-13 39 views
2

在窗体的负载,我需要做的X量检验的,以确定是否要打开或关闭的形式。以下是一个简单的例子。继承的Windows窗体奇怪的行为

public partial class BaseForm : Form 
{ 
    private void BaseForm_Load(object sender, EventArgs e) 
    { 
    if(!IsUserValid()) 
     MessageBox.Show("User is not valid"); 
    } 
    private bool IsUserValid() 
    { 
    List<string> allowedUsernames = new List<string>(); 
    using (SqlConnection con = new SqlConnection(_connectionString)) 
    { 
     //Get a list of usernames, none of which are "Developer" usernames 
    } 
    return allowedUsernames.Any(username => username == Environment.UserName); 
    } 
} 
public partial class DerivedForm : BaseForm 
{ 

} 

上面的例子中,我可以在设计器中完美加载表单,而不管我的用户名是什么。如果我做的另一种形式,DerivedForm和继承的基础然后调用Load,因此会表现出MessageBox然后Close在设计模式的形式,不给我访问设计师,为什么派生WindowsForm需要使用Load事件但基地不?如果你正在做WindowsForms的继承,那么明智的做法是不使用Load事件?

我只是认为这是奇怪的,任何人都知道吗?

+0

我没有看到'override'。你在哪里挂载负载事件? – 2013-02-13 15:03:24

+0

@ P.Brian.Mackey没有一个'override'只是直接继承衍生的基地。 – LukeHennerley 2013-02-13 15:06:06

+1

考虑从UI分离业务逻辑。表单不应该包含名为'IsUserValid'的方法 - 将其移动到引擎类并在其上调用它,然后根据结果决定是否创建(并显示)表单。 – 2013-02-13 15:11:31

回答

1

还有一个question它解决了类似的问题。另外,接受的答案给出了解决此问题的解决方案:https://stackoverflow.com/a/2427420/674700

基本上,你的情况,添加DesignTimeHelper类,只是使用以下修改看出区别:

private void BaseForm_Load(object sender, EventArgs e) 
{ 
    if (!DesignTimeHelper.IsInDesignMode) 
    { 
     if (!IsUserValid()) 
     { 
      MessageBox.Show("User is not valid"); 
     } 
    } 
    else 
    { 
     MessageBox.Show("Called from VS"); 
    } 
}