如何通过编程创建控件事件触发器

9

我想通过编程方式为我的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>

阅读“我想做的是通过编程创建事件触发器来命令ContentControl”,忘记你知道的问题,想象一下你应该理解自己试图表达什么。就我个人而言,我不理解你。 - Dbl
现在更清楚了吗,@AndreasMüller? - Mr. Blond
肯定更好,是的。 - Dbl
https://dev59.com/OU7Sa4cB1Zd3GeqP3Wkv - Sajeetharan
1个回答

17

这是代码中的等效写法:

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

2
非常感谢!你是救命恩人。 :) - Mr. Blond

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接