日期:2014-05-18  浏览次数:20963 次

有关c#的一个问题
我刚学c#,在《c#入门》中有如下代码
private void toolStripButtonItalic_CheckedChanged(object sender, EventArgs e)
  {
  Font oldFont;
  Font newFont;
  bool checkState = ((ToolStripButton)sender).Checked;
  oldFont = this.richTextBox1.SelectionFont;
  if (!checkState)
  newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Italic);
  else
  newFont = new Font(oldFont, oldFont.Style | FontStyle.Italic);
  this.richTextBox1.SelectionFont = newFont;
  this.richTextBox1.Focus();
  this.ToolStripMenuItemItalic.CheckedChanged -= new EventHandler(ToolStripMenuItemItalic_CheckedChanged);
  this.ToolStripMenuItemItalic.Checked = checkState;
  this.ToolStripMenuItemItalic.CheckedChanged += new EventHandler(ToolStripMenuItemItalic_CheckedChanged);

  }
  private void ToolStripMenuItemItalic_CheckedChanged(object sender, EventArgs e)
  {
  this.toolStripButtonItalic.Checked = ToolStripMenuItemItalic.Checked;
  }为什么要加this.ToolStripMenuItemItalic.CheckedChanged -= new EventHandler(ToolStripMenuItemItalic_CheckedChanged);和this.ToolStripMenuItemItalic.CheckedChanged += new EventHandler(ToolStripMenuItemItalic_CheckedChanged);这两行代码?我试着把这两行代码注释掉,和不加运行效果一样,麻烦这里的高手指点一下!




------解决方案--------------------
this.ToolStripMenuItemItalic.CheckedChanged -= new EventHandler(ToolStripMenuItemItalic_CheckedChanged);
是将事件取消掉,
这样后面执行 this.ToolStripMenuItemItalic.Checked = checkState; 这句的时候就不会触发事件;
(如果没注销,这句就会触发事件)
执行完这句重新把事件启用。
this.ToolStripMenuItemItalic.CheckedChanged += new EventHandler(ToolStripMenuItemItalic_CheckedChanged);