如何在IronRuby中实现包含CLR事件的接口

时间:2022-09-02 09:21:23

I'm experimenting with IronRuby and WPF and I'd like to write my own commands. What I have below Is as far as I can figure out.

我正在尝试使用IronRuby和WPF,我想编写自己的命令。我所拥有的是据我所知。

class MyCommand
  include System::Windows::Input::ICommand
  def can_execute()
    true
  end
  def execute()
    puts "I'm being commanded"
  end
end

But the ICommand interface defines the CanExecuteChanged event. How do I implement that in IronRuby?

但ICommand接口定义了CanExecuteChanged事件。我如何在IronRuby中实现它?

Edit: Thanks to Kevin's response

编辑:感谢Kevin的回复

Here's what works based on the 27223 change set of the DLR. The value passed in to can_execute and execute are nil.

这是基于DLR的27223变更集的工作原理。传入can_execute和execute的值为nil。

class MyCommand
  include System::Windows::Input::ICommand
  def add_CanExecuteChagned(h)
    @change_handlers << h
  end
  def remove_CanExecuteChanged(h)
    @change_handlers.remove(h)
  end
  def can_execute(arg)
     @can_execute
  end
  def execute(arg)
    puts "I'm being commanded!"
    @can_execute = false
    @change_handlers.each { |h| h.Invoke(self, System::EventArgs.new) }
  end
  def initialize
    @change_handlers = []
    @can_execute = true
  end
end

1 个解决方案

#1


4  

It looks like this was implemented by Tomas somewhat recently:

看起来这是最近由Tomas实现的:

So you may need to compile from the latest source at github

所以你可能需要从github的最新源代码编译

It looks like you need to add a place for the handler to be passed in and stored. Namely, by adding some add_ and remove_ routines for the specific event handler in question. Something like this might work based on your needs (naive, so please test and flesh out):

看起来您需要为要传递和存储的处理程序添加一个位置。即,通过为相关的特定事件处理程序添加一些add_和remove_例程。这样的事情可能会根据你的需要而有效(天真,所以请测试和充实):

class MyCommand
  include System::Windows::Input::ICommand
  def add_CanExecuteChanged(h)
    @change_handler = h
  end

  def remove_CanExecuteChanged
    @change_handler = nil
  end

  def can_execute()
    true
  end

  def execute()
    #puts "I'm being commanded"
    @change_handler.Invoke if @change_handler
  end
end

#1


4  

It looks like this was implemented by Tomas somewhat recently:

看起来这是最近由Tomas实现的:

So you may need to compile from the latest source at github

所以你可能需要从github的最新源代码编译

It looks like you need to add a place for the handler to be passed in and stored. Namely, by adding some add_ and remove_ routines for the specific event handler in question. Something like this might work based on your needs (naive, so please test and flesh out):

看起来您需要为要传递和存储的处理程序添加一个位置。即,通过为相关的特定事件处理程序添加一些add_和remove_例程。这样的事情可能会根据你的需要而有效(天真,所以请测试和充实):

class MyCommand
  include System::Windows::Input::ICommand
  def add_CanExecuteChanged(h)
    @change_handler = h
  end

  def remove_CanExecuteChanged
    @change_handler = nil
  end

  def can_execute()
    true
  end

  def execute()
    #puts "I'm being commanded"
    @change_handler.Invoke if @change_handler
  end
end