MrTouya
MrTouya

Reputation: 656

How do I bind to an Event that has a delegate using Caliburn.Micro?

Usually I can bind to an event like so:

 cal:Message.Attach="[Event DragStarting] = [Action OnDragStarting($source,$eventArgs)]"

That is when an event has a signature like so:

public event EventHandler<DragDropCancelEventArgs> DragStarting;

How do I Attach to an event that has a delegate like the following:

 public event CanDropEventHandler IDropTargetCanDropElement;
 public delegate bool CanDropEventHandler(object sender, DropEventArgs e);

Any help figuring this out would be greatly appreciated!.

Thanks, S

Upvotes: 0

Views: 435

Answers (1)

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

Why this isn't possible right away ?

Because Caliburn.Micro uses the Blend SDK's interactivity features to convert the syntax ([Event DragStarting] = [Action OnDragStarting($source,$eventArgs)]) to an EventTrigger and the EventTrigger class can't work with events that return a value, and if you think about it is logical, what to do with that return value. In general it is a bad practice for events to return values and you rarely come across such events.

How to fix this ?

The easiest solution would be to change the delegate signature if you could to look like this:

public delegate void CanDropEventHandler(object sender, DropEventArgs eventArgs);

Then you convert that bool value returned to a public property on the DropEventArgs class, after that Caliburn.Micro syntax will work correctly.

What if you can't change the delegate's signature ?

Then you will have to create an Adapter by deriving from the type that owns that event or by wrapping that type if it is sealed and then declare a new event with the signature i showed you above, and then listen to the new event.

Is there any other way ?

Maybe you can create a custom event trigger that derives from TriggerBase<T> which can work with events that have return values but this is an advanced technique that is a bit hard to implement, and anyway you won't to able to use CM's syntax anymore.

Edit: What i mean by that make the DropEventArgs class have that property instead of returning it from the delegate, so the DropEventArgs becomes something like this:

class DropEventArgs : EventArgs {
    public bool CanDrop {get; set;} // OR CHOOSE WHATEVER NAME YOU WANT
}

and the delegate becomes like i showed you above.

Upvotes: 1

Related Questions