Search code examples
event-handlingcompact-frameworkmvpopennetcfscsf

How to make custom event for all SmartParts?


There is C# Project (.NET CF) that uses OpenNETCF.IOC.(UI) library.

Actual situation: In Base Form OnKeyDown event is handled and custom event can be raised (for example if user ESC button pressed). This event can be handled in descendant forms.

After refactoring: Base Form is now container form. All descendant forms are now SmartParts. How should I now raise custom event from container form to 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;
     ...
 }

Solution

  • I'm not sure I fully understand the question, but I'll try to answer. If you want to raise an event from a child class, but that event is defined in a base class, you should use a "helper" method in the base:

    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);
       }
    }
    

    If you're trying to go the other way, having the parent notify the children, then it's more like this:

    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 
        }
    }