2009-10-25 133 views
0

在WinForm:
alt text http://i36.tinypic.com/2r26a77.png在WinForm中处理CheckBox控件的最佳做法是什么?

代码:

using System; 
using System.Windows.Forms; 

namespace DemoApp 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void checkBox1_CheckedChanged(object sender, EventArgs e) 
     { 
      groupBox2.Enabled = checkBox1.Checked; 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      SaveSetings(); 
     } 

     private void SaveSetings() 
     { 
      Properties.Settings.Default.UserName = textBox1.Text; 
      Properties.Settings.Default.pass = textBox2.Text; 
      Properties.Settings.Default.userproxy = checkBox1.Checked; 
      Properties.Settings.Default.proxy = textBox3.Text; 
      Properties.Settings.Default.proxy_port = textBox4.Text; 
      Properties.Settings.Default.Save(); 
     } 

     //private void Form1_Load(object sender, EventArgs e) 
     //{ 
     // checkBox1.Refresh(); 
     // groupBox2.Enabled = checkBox1.Checked; 
     //} 
    } 
} 

为u可以在代码中我有“使用代理服务器”复选框选择应使groupbox1反之亦然时,这是看到的。问题是当表单从“user.config”加载设置时,即使未选中检查控件组1被启用。处理这种情况的一种方法是检查在窗体加载事件即

groupBox2.Enabled = checkBox1.Checked; 

控制是否有任何其他要做到这一点,让我的应用程序更DINAMIC? 我问这个问题的原因是因为可能会出现多个控件位于同一个表单上的情况,我认为这会变得令人困惑。

回答

2

我平时喜欢做两两件事不同的相比,你的代码示例:

  • 而不是创建控件之间的耦合依赖,创建一个描述的状态,而不是
  • 收集代码的值改变UI状态的控件(如VisibleEnabled)合并成一个方法,并在需要时调用该方法。

实施例:

private bool _useProxy; 
private bool UseProxy 
{ 
    get 
    { 
     return _useProxy; 
    } 
    set 
    { 
     bool valueChanged = _useProxy != value; 
     _useProxy = value; 
     if (valueChanged) 
     { 
      SetControlStates(); 
     } 
    } 
} 

private void SetControlStates() 
{ 
    groupBox2.Enabled = this.UseProxy; 
    checkBox1.Checked = this.UseProxy; 
} 

private void checkBox1_CheckedChanged(object sender, EventArgs 
    this.UseProxy = checkBox1.Checked; 
} 

然后,在,从配置文件中读出时,则简单地用从该文件的值分配this.UseProxy。通过这种方式,不同的控制方式不会以相同的方式相互依赖,而是依赖于它们与之相关的状态。

+0

你的代码可以通过的方式来优化一点点...... 设置 { 如果(_useProxy =价值!) { _useProxy =值; SetControlStates(); } } 是UseProxy的setter所需的全部:) – mike 2009-10-25 12:23:58

0

in Form.Loaded handler set groupBox2.Enabled = Properties.Settings.Default.userproxy;

相关问题