我想以编程方式为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>
答案 0 :(得分:12)
这里是代码中的等价物:
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);
}