2013-03-28 24 views
1

我试图轻松地创建自定义复选框。我想通过检查状态在每个复选框的顶部绘制图像。我如何创建单个事件处理程序全部复选框?我有很多的复选框,我不想为它编写每个事件处理程序:所有复选框的单个事件处理程序

private void checkbox1_Paint(object sender, PaintEventArgs e) 
    { 
     Rectangle rect = new Rectangle(0, 0, 16, 16); 
     if (checkbox1.Checked) 
     { 
      e.Graphics.DrawImage(Properties.Resources.checkbox_checked, rect); 
     } 
     else 
     { 
      e.Graphics.DrawImage(Properties.Resources.checkbox_unchecked, rect); 
     } 
    } 
    private void checkbox2_Paint(object sender, PaintEventArgs e) 
    { 
     Rectangle rect = new Rectangle(0, 0, 16, 16); 
     if (checkbox2.Checked) 
     { 
      e.Graphics.DrawImage(Properties.Resources.checkbox_checked, rect); 
     } 
     else 
     { 
      e.Graphics.DrawImage(Properties.Resources.checkbox_unchecked, rect); 
     } 
    } 
    // etc... 
+1

如果这是WPF,你可以在父母的勾选或者处理处理这个问题,使用事件冒泡机制。 – David

+0

@大卫的任何例子? –

+0

参考这本书:WPF释放,P161 – David

回答

0

我其实自己找到了答案。这比手动将绘画事件分配给每个复选框要容易,因为它是以编程方式完成的。

public void SetAllCheckboxes(Control where) 
{ 
    foreach (Control control in where.Controls) 
    { 
     if (control.GetType().Name == "CheckBox") 
      control.Paint += new PaintEventHandler(this.checkbox_Paint); 
     else if (control.Controls.Count > 0) 
      SetAllCheckboxes(control); 
    } 
} 

,然后就在调用它:

SetAllCheckboxes(this); 
1

你可以使用同样的方法任意次数,只在Paint事件分配给它(通过设计或代码) 。

将当前复选框强制转换为复选框。

private void checkbox1_Paint(object sender, PaintEventArgs e) 
{ 
CheckBox chk = sender as CheckBox; 
.. 
} 
1

我认为这是基于上下文的Windows窗体?

您选择每个checkbox(可以多选在窗体设计器),单击Properties面板的闪电,发现Paint事件,把你方法名称:checkbox1_Paint ,在那里。

4

将此处理程序分配给所有复选框。请注意我是如何将sender投射到CheckBox以获得触发事件的控件。

private void checkbox_Paint(object sender, PaintEventArgs e) 
{ 
    var checkbox = sender as CheckBox // Here you get the current checkbox 
    Rectangle rect = new Rectangle(0, 0, 16, 16); 
    if (checkbox.Checked) 
    { 
     e.Graphics.DrawImage(Properties.Resources.checkbox_checked, rect); 
    } 
    else 
    { 
     e.Graphics.DrawImage(Properties.Resources.checkbox_unchecked, rect); 
    } 
} 
相关问题