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>
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With