Search code examples
ironruby

How do you raise a .Net event from an IronRuby class?


I'm trying to figure out how to implement an event in a ruby class. Specifically, I am trying to make my class implement an interface (INotifyPropertyChanged) that includes an event (PropertyChanged). I can create my add_PropertyChanged and remove_PropertyChanged methods... but then what?

This is what my class looks like so far:

class TestClass
    include System::ComponentModel::INotifyPropertyChanged

    def add_PropertyChanged(handler)
    end

    def remove_PropertyChanged(handler)
    end
end

Solution

  • OK, I figured it out. Here is how you do it:

    class TestClass
        include System::ComponentModel::INotifyPropertyChanged
    
        def initialize
            @change_handlers = []
        end
    
        def add_PropertyChanged(handler)
            @change_handlers << handler
        end
    
        def remove_PropertyChanged(handler)
            @change_handlers.delete(handler)
        end
    
        def NotifyPropertyChanged(name)
            @change_handlers.each { |h| h.invoke(self, System::ComponentModel::PropertyChangedEventArgs.new(name)) }
        end
    end