【问题标题】:How to make custom event for all SmartParts?如何为所有 SmartParts 制作自定义事件?
【发布时间】:2013-09-02 06:50:24
【问题描述】:

有使用 OpenNETCF.IOC.(UI) 库的 C# 项目 (.NET CF)。

实际情况: 在基本表单中处理 OnKeyDown 事件并且可以引发自定义事件(例如,如果按下用户 ESC 按钮)。此事件可以以后代形式处理。

重构后: 基本形式现在是容器形式。所有后代形式现在都是 SmartPart。 我现在应该如何将自定义事件从容器表单引发到 SmartParts?

// Base form
private void BaseForm_KeyDown(object sender, KeyEventArgs e)
{
   // Handle ESC button
   if (e.KeyCode == Keys.Escape || e.KeyValue == SomeOtherESCCode)
   {
       this.ButtonESCClicked(sender, new EventArgs());
   }
 }

 // Descendant form
 private void frmMyForm_ButtonESCClicked(object sender, EventArgs e)
 {
     this.AutoValidate = AutoValidate.Disable;
     ...
 }

【问题讨论】:

    标签: event-handling compact-framework mvp opennetcf scsf


    【解决方案1】:

    我不确定我是否完全理解这个问题,但我会尽力回答。如果您想从子类中引发事件,但该事件是在基类中定义的,则应在基类中使用“帮助器”方法:

    public abstract ParentClass : Smartpart
    {
        public event EventHandler MyEvent;
    
        protected void RaiseMyEvent(EventArgs e)
        {
            var handler = MyEvent;
            if(handler != null) handler(this, e);
        }
    }
    
    public ChildClass : ParentClass
    {
       void Foo()
       {
           // rais an event defined in a parent
           RaiseMyEvent(EventArgs.Empty);
       }
    }
    

    如果你想换一种方式,让父母通知孩子,那么它更像是这样:

    public abstract ParentClass : Smartpart
    {
        protected virtual void OnMyEvent(EventArgs e) { } 
    
       void Foo()
       {
           // something happened, notify any child that wishes to know
           OnMyEvent(EventArgs.Empty);
    
           // you could optionally raise an event here so others could subscribe, too
       }
    }
    
    public ChildClass : ParentClass
    {
        protected override void OnMyEvent(EventArgs e)
        {
            // this will get called by the parent/base class 
        }
    }
    

    【讨论】:

    • 好的,非常感谢。我提到我需要/我必须始终为所有自定义 SmartPart 创建父 SmartPart?
    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多