如何以编程方式创建用于控制的事件触发器 [英] How to create an event trigger for control programmatically

查看:18
本文介绍了如何以编程方式创建用于控制的事件触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式为我的 ContentControl 创建一个事件触发器.我想获得与使用此 xaml 代码相同的结果.包括 - 命令、命令参数、事件名称

它在我的 xaml 代码中的外观:

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>

推荐答案

以下是等效代码:

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

这篇关于如何以编程方式创建用于控制的事件触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆