wpf 如何以编程方式创建用于控制的事件触发器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24808950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:10:28 来源:igfitidea点击:
How to create an event trigger for control programmatically
提问by Mr. Blond
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 创建一个事件触发器。我想获得与使用此 xaml 代码相同的结果。包括 - 命令、命令参数、事件名称
在我的 xaml 代码中的外观:
<ContentControl>
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding ButtonClickCommand}" CommandParameter="btnAdd"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ContentControl>
回答by McGarnagle
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);
}

