当Control.ParentChanged事件发生时?

时间:2010-12-02 14:28:57

标签: c# winforms

我在MSDN上阅读了有关Control.ParentChanged事件的信息 http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parentchanged(VS.71).aspx

但我不明白示例代码:源代码中根本没有出现ParentChanged?

private void currencyTextBox_TextChanged(object sender, EventArgs e)
{
   try
   {
      // Convert the text to a Double and determine if it is a negative number.
      if(double.Parse(currencyTextBox.Text) < 0)
      {
         // If the number is negative, display it in Red.
         currencyTextBox.ForeColor = Color.Red;
      }
      else
      {
         // If the number is not negative, display it in Black.
         currencyTextBox.ForeColor = Color.Black;
      }
   }
   catch
   {
      // If there is an error, display the text using the system colors.
      currencyTextBox.ForeColor = SystemColors.ControlText;
   }
}

所以我不明白什么是Control.ParentChanged事件。

2 个答案:

答案 0 :(得分:4)

呵呵,他们只是想出一个很好的例子。而是通过显示一个通用的FooChanged事件处理程序而受到惩罚。是的,没用。

自己实现ParentChanged事件处理程序是很不寻常的。这在Winforms内部是一个大问题,像BackColor,ForeColor,Font这样的属性是'环境'属性。如果它们没有被默认覆盖,那么它们将获得Parent的值。这当然意味着注意到父母改变了真的很重要。 winforms代码已经完成了它,你很少需要担心它。除非你当然创建自己的环境属性。

答案 1 :(得分:0)

在别处会有另一段代码将其注册为事件处理程序:

currencyTextBox.ParentChanged += new EventHandler(currencyTextBox_TextChanged);

但是,我同意 - 方法名称具有误导性。

当您将此控件的父控件更改为其他父控件时,将触发此事件处理程序。

您可能需要阅读raising and consuming events

相关问题