How to create an event trigger for control programmatically

后端 未结 1 613
挽巷
挽巷 2021-02-15 15:53

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,

1条回答
  •  暖寄归人
    2021-02-15 16:52

    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);
    }
    

    0 讨论(0)
提交回复
热议问题