views:

145

answers:

2

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  A: 

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.

Pavel Minaev
tyndall
The remove example uses this sequence: `button.click( button.click.remove(on_click)`
Pavel Minaev
I presume that this implies that calling `click` several times with different arguments (or even the same argument) will register several handlers, same as in C#.
Pavel Minaev
tyndall
I'm getting an error on this syntax (I think) - syntax error, unexpected IDENTIFIER
tyndall
On which one - the one with `do`, or the one with a named function?
Pavel Minaev
I've played with it a bit, and it seems that syntax for IRB events is still very much in flux, and the only foolproof way is to always use blocks. If you need to call a named method, wrap the call inside the block, i.e. `button1.click do |sender, args| foo(sender, args) end`. If you need to unregister the handler at some later point, make a `Proc` out of that block and store it in a variable, as in Shay's answer.
Pavel Minaev
Error was something else. thanks.
tyndall
+1  A: 

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
Shay Friedman
Also cool way to do it. +1
tyndall
Keep in mind you can get those "Proc" objects from a method as well: "button1.click.add method(:foo)", where :foo is a method name
Jimmy Schementi