IronRuby and Handling XAML UI Events

2019-07-25 05:34发布

问题:

What it is the most brief and concise way of adding event handlers to UI elements in XAML via an IronRuby script? Assumption: the code to add the event handler would be written in the IronRuby script and the code to handle the event would be in the same IronRuby script.

I'd like the equivalent of the following code but in IronRuby. Handling a simple button1 click event.

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        button1.Click += new RoutedEventHandler(button1_Click);
    }

    void button1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Hello World!");
    }
}

回答1:

So far as I know, .NET events are exposed as methods taking blocks in IronRuby. So, you can write:

button1.click do |sender, args|
    MessageBox.show("Hello World!")
end

This covers other options.



回答2:

You can also use add to subscribe an event if it makes more sense to you.

p = Proc.new do |sender, args| 
  MessageBox.show("Hello  World!")
end

# Subscribe
button1.click.add p

# Unsubscribe
button1.click.remove p