9

I want to create an event trigger for my ContentControl programmatically. I want to achieve the same result as i would use this xaml code. Including - Command, CommandParameter, EventName

How it looks in my xaml code:

<ContentControl>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding ButtonClickCommand}" CommandParameter="btnAdd"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ContentControl>
Mr. Blond
  • 1,113
  • 2
  • 18
  • 41
  • Read "What i want to do is to create an event trigger to command for ContentControl programmatically.", forget that you know your problem, and imagine you are supposed to understand what you are trying to say. I for one don't understand you – Dbl Jul 17 '14 at 16:39
  • Is it more clear now @AndreasMüller? – Mr. Blond Jul 17 '14 at 16:59
  • definitely better, yes – Dbl Jul 17 '14 at 17:08
  • http://stackoverflow.com/questions/3033839/firing-mouseleftbuttondown-event-programmatically – Sajeetharan Jul 17 '14 at 18:10

1 Answers1

17

Here's the equivalent in code:

void SetTrigger(ContentControl contentControl)
{
    // create the command action and bind the command to it
    var invokeCommandAction = new InvokeCommandAction { CommandParameter = "btnAdd" };
    var binding = new Binding { Path = new PropertyPath("ButtonClickCommand") };
    BindingOperations.SetBinding(invokeCommandAction, InvokeCommandAction.CommandProperty, binding);

    // create the event trigger and add the command action to it
    var eventTrigger = new System.Windows.Interactivity.EventTrigger { EventName = "PreviewMouseLeftButtonDown" };
    eventTrigger.Actions.Add(invokeCommandAction);

    // attach the trigger to the control
    var triggers = Interaction.GetTriggers(contentControl);
    triggers.Add(eventTrigger);
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260