代码之家  ›  专栏  ›  技术社区  ›  Scott Marlowe

如何将C?事件处理程序标记为“已处理”?

  •  3
  • Scott Marlowe  · 技术社区  · 15 年前

    假设我在表单上有一个按钮,如果满足某个条件,我想禁用它。是否有一种方法来检查按钮的“ISS启用”事件处理程序中的这个条件,并修改启用状态,使得第二次设置启用状态不会触发对ISBASE事件处理程序的另一次调用吗?

    让我演示一下:

    private void ExportResults_IsEnabledChanged (object sender, DependencyPropertyChangedEventArgs e)
    {
     if (some condition)
     {
      uxExportResults.IsEnabled = false; // this will cause another call to the event handler, eventually resulting in a stack overflow
     }
    }
    

    假设我在别处触发了这个事件。

    3 回复  |  直到 15 年前
        1
  •  4
  •   Jon B    15 年前
    if (someCondition && uxExportResults.IsEnabled) { ... }
    

    这将仅在启用控件时禁用它。

        2
  •  3
  •   Paul Williams    15 年前

    另一个选项是暂时禁用事件,如下所示:

    private void ExportResults_IsEnabledChanged (object sender, DependencyPropertyChangedEventArgs e)
    {
        if (some condition)
        {
            uxExportResults.IsEnabledChanged -= ExportResults_IsEnabledChanged;
            try
            {
                uxExportResults.IsEnabled = false; // this will cause another call to the event handler, eventually resulting in a stack overflow
            }
            finally
            {
                uxExportResults.IsEnabledChanged += ExportResults_IsEnabledChanged;
            }
        }
    }
    
        3
  •  2
  •   Will Eddins ianpoley    15 年前

    最简单的解决方案是在设置之前检查isenabled的值。

    private void ExportResults_IsEnabledChanged (object sender, DependencyPropertyChangedEventArgs e)
    {
      if (uxExportResults.IsEnabled == true)
      {
        uxExportResults.IsEnabled = false;
      }
    }
    

    另外,如果您能够更改按钮的代码,则除非值实际更改,否则isenabled不应发送事件。

    public bool IsEnabled
    {
      get { return isEnabled; }
      set
      {
        if(isEnabled != value)
        {
          isEnabled = value;
          IsEnabledChanged(this,args);
        }
      }
    }