Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an event trigger for control programmatically

Tags:

c#

wpf

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>
like image 377
Mr. Blond Avatar asked Jul 17 '14 16:07

Mr. Blond


1 Answers

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);
}
like image 128
McGarnagle Avatar answered Nov 12 '22 09:11

McGarnagle