Greg Gum Greg Gum - 2 months ago 10
C# Question

How to Bind Click Event to ViewModel when creating control in code

Typically, I create the view in XAML, and bind events to the viewmodel using Caliburn.Micro.

<Button cal:Message.Attach="[MouseLeftButtonUp]=[ModifyList($source)]" />


However, I now need to create the button in code, based on configuration data.

The code is not in the code-behind, it's in a factory class.

Button button = new Button() { Content = "Click Me" };


So the question is how to wire up the event?

Answer

I've never done this before, so this might not be the best way, but it does appear to work.

I've written an extension method below that should make it pretty simple to attach an ActionMessage to any event of any control.

public static class UIElementExtension {
    public static void AttachActionMessage(this DependancyObject control, string eventName, string methodName, object parameter) {
        var action = new ActionMessage();
        action.MethodName = methodName;
        action.Parameters.Add(new Parameter { Value = parameter });

        var trigger = new System.Windows.Interactivity.EventTrigger();
        trigger.EventName = eventName;
        trigger.SourceObject = control;
        trigger.Actions.Add(action);

        Interaction.GetTriggers(control).Add(trigger);
    }
}

To use it, simply create your control and call AttachActionMessage():

var button = new Button { Content = "Click Me" };
button.AttachActionMessage("Click", "ModifyList", DataContext);