c# – 如何以编程方式为控件创建事件触发器

我想以编程方式为ContentControl创建一个事件触发器.我希望获得与使用此xaml代码相同的结果.包括 – Command,CommandParameter,EventName
它在我的xaml代码中的外观如何:
<ContentControl>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding ButtonClickCommand}" CommandParameter="btnAdd"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ContentControl>

解决方法

这是代码中的等价物:
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);
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...